NestJs Exception Filters: Part 02

Udara Abeythilake
5 min readJul 3, 2022

Introduction

What is exception handling?

As you all know, the exception is a mechanism to handle runtime errors so that the normal flow of the application can be maintained. There can be many types of runtime errors that may occur that we are not expecting. In order to get to know the root of the runtime error and identify the place where the error occurred exception handling may help.

NestJs has a built-in exception layer that can track any unhandled exception in the application. These unhandled exceptions are followed by this layer and send user-friendly and meaningful responses. If the exception is not recognized by the exception built-in layer on the NestJs it will throw a response like below

Standard exception handling

Nest provides built-in HttpException classes which are defined from @nestjs/common package. For REST API applications, HttpExcetion is the best method to send a response when there is an error condition occurring on the runtime.

For example, let’s say a user calling API to get all available fuel stations and it throws an error with HttpException like below

When a user calls this API user will get an error like below

The constructor arguments define the response and the HTTP response status code.

  • The `response` argument (required) defines the JSON response body.
  • The `status` argument (required) defines the HTTP Status Code.

By default, the JSON response body contains two properties:

  • `statusCode`: the HttpStatus Code.
  • `message`: a short description of the HTTP error by default; override this by supplying a string in the `response` parameter.

To override the entire JSON response body, we can pass an object to the `createBody` method. Nest will serialize the object and return it as the JSON response body. The `status` argument is required and should be a valid HTTP status code.

The best practice is to use the `HttpStatus` enum imported from `nestjs/common`. Below are the values available at HttpStatus enum

  • CONTINUE = 100
  • SWITCHING_PROTOCOLS = 101
  • PROCESSING = 102
  • EARLYHINTS = 103
  • OK = 200
  • CREATED = 201
  • ACCEPTED = 202
  • NON_AUTHORITATIVE_INFORMATION = 203
  • NO_CONTENT = 204
  • RESET_CONTENT = 205
  • PARTIAL_CONTENT = 206
  • AMBIGUOUS = 300
  • MOVED_PERMANENTLY = 301
  • FOUND = 302
  • SEE_OTHER = 303
  • NOT_MODIFIED = 304
  • TEMPORARY_REDIRECT = 307
  • PERMANENT_REDIRECT = 308
  • BAD_REQUEST = 400
  • UNAUTHORIZED = 401
  • PAYMENT_REQUIRED = 402
  • FORBIDDEN = 403
  • NOT_FOUND = 404
  • METHOD_NOT_ALLOWED = 405
  • NOT_ACCEPTABLE = 406
  • PROXY_AUTHENTICATION_REQUIRED = 407
  • REQUEST_TIMEOUT = 408
  • CONFLICT = 409
  • GONE = 410
  • LENGTH_REQUIRED = 411
  • PRECONDITION_FAILED = 412
  • PAYLOAD_TOO_LARGE = 413
  • URI_TOO_LONG = 414
  • UNSUPPORTED_MEDIA_TYPE = 415
  • REQUESTED_RANGE_NOT_SATISFIABLE = 416
  • EXPECTATION_FAILED = 417
  • I_AM_A_TEAPOT = 418
  • MISDIRECTED = 421
  • UNPROCESSABLE_ENTITY = 422
  • FAILED_DEPENDENCY = 424
  • PRECONDITION_REQUIRED = 428
  • TOO_MANY_REQUESTS = 429
  • INTERNAL_SERVER_ERROR = 500
  • NOT_IMPLEMENTED = 501
  • BAD_GATEWAY = 502
  • SERVICE_UNAVAILABLE = 503
  • GATEWAY_TIMEOUT = 504
  • HTTP_VERSION_NOT_SUPPORTED = 505

Customize Exception

In NestJs you can inherit HttpException and create customized exceptions classes. When you create a custom class Nest will identify the exception and do the useful exception handling automatically.

After creating this exception class, we can call it the place we want.

When this endpoint triggers it will throw the above exception and can get a response as below

Built-in HTTP Exceptions

Nest provides a set of standard exceptions that inherit from the base HttpException. These are exposed from the @nestjs/common package, and represent many of the most common HTTP exceptions:

  • BadRequestException
  • UnauthorizedException
  • NotFoundException
  • ForbiddenException
  • NotAcceptableException
  • RequestTimeoutException
  • ConflictException
  • GoneException
  • HttpVersionNotSupportedException
  • PayloadTooLargeException
  • UnsupportedMediaTypeException
  • UnprocessableEntityException
  • InternalServerErrorException
  • NotImplementedException
  • ImATeapotException
  • MethodNotAllowedException
  • BadGatewayException
  • ServiceUnavailableException
  • GatewayTimeoutException
  • PreconditionFailedException

Exception Filters

NestJs built-in filter can track most of the exceptions you need to handle when implementing the nest application. In case you want full control over the exception filter you can create your own exception filter. For example, you need to add a logging mechanism to your application if any exception is thrown from the app so that you can track the root cause of the exception. In this situation, the custom exception filter will be a good solution. Below you can see a sample exception filter class

Below are the definitions of each parameter of the catch() method.

exception: the exception object being process

host: powerful utility object that is used to obtain a reference to the request and response.

Binding Filters

After creating the exception filter, we have to bind that filter to the application. Let’s see how to do that. There are multiple levels to bind the exception filters to the application.

  • Method scoped
  • Controller scoped
  • Global scoped

Method scoped

We can add the @UseFilters() decorator for each method if you need to use that filter.

Here, we created the instance of HttpExceptionFilter in place. Alternatively, you may pass the class (instead of an instance), leaving responsibility for instantiation to the framework, and enabling dependency injection.

Controller scoped

We can add the filter to the entire controller at once without adding to each method

Global scoped

To create a global-scoped filter, you would do the following:

Global-scoped filters are used across the whole application, for every controller and every route handler. In terms of dependency injection, global filters registered from outside of any module (with useGlobalFilters() as in the example above) cannot inject dependencies since this is done outside the context of any module. In order to solve this issue, you can register a global-scoped filter directly from any module using the following construction:

Conclusion

In this tutorial, you learn how to handle exceptions in NestJs application. In NestJs there are built-in exception handlers. If you need you can create customize exception handlers. And also, we have discussed how to create exception filters and apply that filter at different levels of the application.

--

--