Filter basic structure

First steps before getting into the core logic.

Let's create it in the database folder, for better semantics and organization.

nest g f database/exception-filters/not-found-exception

We now have a basic structure to begin with. The first thing to be noticed is the @Catch() decorator over the filter. Here, we define what types of errors it must catch in order to handle them. In our case, we want to catch the EntityNotFoundError, so put it inside the parentheses. We shall also remove the generic as we won't be needing it, and set the type of the exception parameter as this error. We should have the following result:

@Catch(EntityNotFoundError)
export class NotFoundExceptionFilter implements ExceptionFilter {
  catch(exception: EntityNotFoundError, host: ArgumentsHost) {}
}

The catch() method is invoked when the error/exception is catched. it has as parameters the catched exception and the host, which allows for accessing the response to be sent. In here, we'll return a response with the status NotFound and an appropriate message.

The first step is to obtain the response from the host.

const response = host.switchToHttp().getResponse<Response>();

The Response type is from express.

Then, we'll create a standard error structure to have errors similar to Nest.

Last updated