Skip to content

Class: default ​

AdonisJS middleware that intercepts errors thrown during HTTP requests and formats the responses in a consistent, client-friendly manner. Supports multiple error types including Vine validation errors, Joi validation errors, framework exceptions, and generic errors.

The middleware provides:

  • Consistent error response formatting across all error types
  • Event-driven error handling for monitoring and logging
  • Content negotiation supporting JSON and YAML responses
  • Recursive error cause handling to preserve error chains
  • Configurable headers for CORS, security, and custom requirements

Examples ​

typescript
// Basic usage with default configuration
const middleware = new ResourcefulErrorMiddleware({});
router.use(middleware.handle);

// Advanced usage with event handlers and custom headers
const middleware = new ResourcefulErrorMiddleware({
  onVineValidationError: (error) => logger.warn("Validation failed", error),
  onException: (error) => monitoring.captureException(error),
  onAny: (error) => analytics.trackError(error),
  headers: {
    "X-API-Version": "1.0",
    "Access-Control-Allow-Origin": "*",
  },
});
router.use(middleware.handle);
typescript
// Standalone usage outside of resourceful routes
import ResourcefulErrorMiddleware from "@nhtio/lucid-resourceful/middlewares/resourceful_error";

const errorHandler = new ResourcefulErrorMiddleware({
  onException: (error) => logger.error(error),
  headers: { "X-Error-Handler": "resourceful" },
});

router.use(errorHandler.handle);

Constructors ​

Constructor ​

ts
new default(opts: ResourcefulErrorMiddlewareOptions): ResourcefulErrorMiddleware;

Creates a new instance of ResourcefulErrorMiddleware with the specified configuration.

Parameters ​

ParameterTypeDescription
optsResourcefulErrorMiddlewareOptionsConfiguration options for the middleware

Returns ​

ResourcefulErrorMiddleware

Example ​

typescript
const middleware = new ResourcefulErrorMiddleware({
  onVineValidationError: (error) => console.error("Validation:", error),
  onException: (error) => monitoring.captureException(error),
  asYaml: true,
  headers: { "X-API-Version": "1.0" },
});

Methods ​

handle() ​

ts
handle(ctx: HttpContext, next: NextFn): Promise<void>;

AdonisJS middleware handler that intercepts and processes errors during request execution. This method should be used as middleware in your route definitions.

Parameters ​

ParameterTypeDescription
ctxHttpContextThe HTTP context object containing request and response information
nextNextFnThe next function to call in the middleware chain

Returns ​

Promise<void>

Example ​

typescript
const middleware = new ResourcefulErrorMiddleware({});
router.use(middleware.handle);

// Or bind it to specific routes
router.get("/api/users", UserController.index).use([middleware.handle]);

onError() ​

ts
onError(ctx: HttpContext, error: unknown): void;

Processes a caught error, emits appropriate events, and sends a formatted response. This method handles error classification, event emission, content negotiation, and response formatting.

Parameters ​

ParameterTypeDescription
ctxHttpContextThe HTTP context object
errorunknownThe error that was caught during request processing

Returns ​

void

Example ​

typescript
// Typically called automatically by the handle method, but can be used directly
try {
  // Some operation that might throw
} catch (error) {
  middleware.onError(ctx, error);
}

handle() ​

ts
static handle(
   error: unknown,
   ctx: HttpContext,
   opts: ResourcefulErrorMiddlewareOptions): void;

Handles errors thrown during request processing. This method is meant to be integrated with the AdonisJS HttpExceptionHandler

Parameters ​

ParameterTypeDescription
errorunknownThe error that was thrown
ctxHttpContextThe HTTP context object
optsResourcefulErrorMiddlewareOptionsConfiguration options for the middleware

Returns ​

void

A Promise that resolves to the error response


shouldHandle() ​

ts
static shouldHandle(ctx: HttpContext): boolean;

Determines if the middleware should handle the request based on the desired response format. If the desired format is HTML, it returns false to allow other handlers to process the request. Otherwise, it returns true to indicate that this middleware should handle the error response.

Parameters ​

ParameterTypeDescription
ctxHttpContextThe HTTP context object containing request and response information

Returns ​

boolean

A boolean indicating whether this middleware should handle the request


usable() ​

ts
static usable(opts: ResourcefulErrorMiddlewareOptions): (ctx: HttpContext, next: NextFn) => Promise<void>;

Creates a usable middleware function that can be applied directly to AdonisJS routes.

Parameters ​

ParameterTypeDescription
optsResourcefulErrorMiddlewareOptionsConfiguration options for the middleware

Returns ​

A middleware function that can be used in AdonisJS routes

ts
(ctx: HttpContext, next: NextFn): Promise<void>;
Parameters ​
ParameterType
ctxHttpContext
nextNextFn
Returns ​

Promise<void>