Skip to main content

Error Filter

Error filters allow you to catch and process errors that occur during request handling. They provide a centralized way to transform application errors into appropriate HTTP responses, keeping your controllers clean and focused on business logic.

Error filter and injectable decorators

You don't need to add @injectable(). The @CatchError() decorator already applies it for you.

How Error Filters Work

Error filters are classes that implement the ErrorFilter interface and are decorated with @CatchError(). When an error occurs during request processing, Inversify HTTP looks for error filters that can handle that specific error type and delegates the error handling to them.

The error filter can then:

  • Transform the error into an appropriate HTTP response
  • Log the error for debugging purposes
  • Add context or sanitize error messages
  • Return custom error responses based on the error type

Basic Example

Here's a complete example showing how to create a custom error, an error filter to handle it, and a controller that uses the error filter:

Custom Error

First, create a custom error class:

export class InvalidOperationError extends Error {
constructor(message: string = 'Invalid operation', options?: ErrorOptions) {
super(`[InvalidOperationError]: ${message}`, options);
}
}

Error Filter

Create an error filter that catches the custom error and returns an appropriate HTTP response:

@CatchError(InvalidOperationError)
export class InvalidOperationErrorFilter
implements ErrorFilter<InvalidOperationError>
{
public catch(error: InvalidOperationError): void {
throw new UnprocessableEntityHttpResponse(error.message, undefined, {
cause: error,
});
}
}

Controller

Apply the error filter to a controller using the @UseErrorFilter() decorator:

@Controller('/products')
@UseErrorFilter(InvalidOperationErrorFilter)
export class ProductController {
@Get('/:id/validate')
public async validateProduct(): Promise<void> {
throw new InvalidOperationError('Product validation failed');
}
}

Attaching error filters

Use the UseErrorFilter decorator at the controller level (applies to all routes) or at the method level (applies to one route).

Global error filters can be registered using the InversifyHttpAdapter.