Error Handling

Robust error handling is essential for creating reliable APIs. Jetpath centralizes error handling in middleware for consistent error management.

Philosophy

Instead of scattered try...catch blocks, Jetpath’s approach relies on:

  1. Signaling Errors: Using throw new Error()
  2. Centralized Catching: Intercepting errors in middleware
  3. Standardized Responses: Sending consistent error responses

Throwing Errors

When processing cannot continue normally, signal an error using ctx.send(error, <status code>).

Using ctx.send(error, <status code>)

Using throw new Error()

For unexpected internal errors:

try {
  const result = await riskyOperation();
} catch (error) {
  console.error("Internal error:", error);
  throw new Error("Internal processing error");
}

Middleware Error Handling

The post-handler function in middleware handles errors from route handlers and validation.

Error Handling Structure

return (ctx, err?: Error) => {
  if (err) {
    // 1. Log error
    console.error({
      message: `Request Error: ${err.message}`,
      stack: err.stack,
      requestId: ctx.get("X-Request-ID"),
      url: ctx.request.url,
      method: ctx.request.method,
    });
    // 2. Set status code
    ctx.code = ctx.code >= 400 ? ctx.code : 500;
    // 3. Format response
    const errorMessage = (ctx.code >= 500 && process.env.NODE_ENV === 'production')
      ? "Internal Server Error"
      : err.message || "An unexpected error occurred";
    const errorResponse = {
      error: {
        message: errorMessage,
        code: ctx.code,
        requestId: ctx.get("X-Request-ID"),
      },
      timestamp: new Date().toISOString(),
    };
    // 4. Send response
    ctx.set("Content-Type", "application/json");
    ctx.send(errorResponse);
    // 5. Stop processing
    return;
  }
  // Handle successful responses
};

Error Cases

Best Practices

Next Steps