Nest.js exception filters provide a way to intercept and handle exceptions globally or on a per-controller basis.

They let you centralize error-handling logic, format error responses, and provide consistent error handling across your application. Learn about exception filters and how to use them to appropriately handle application errors.

Default Error Handling in Nest.js

By default, Nest.js has an exception layer that deals with any exceptions that your application code doesn’t handle.

When an unhandled error occurs in your application, Nest.js catches it and returns a 500 internal server error to the client. The JSON that Nest.js returns in this case looks like this:

If the error object that your code throws contains astatusCodeand amessage, Nest.js will return those values instead of the default response.

To avoid this generic behavior, and send a more meaningful error response to the client, you need to diligently handle all the errors that might occur in your application. you’re able to achieve this using Nest.js’ built-in or custom exception filters.

Creating a Custom Exception Filter

To demonstrate the process of creating a custom exception filter, try creating one that will handle all HTTP exceptions.

Start with a file calledhttp.exception.tsand add the following imports to it:

These imports serve the following purposes.

Next, create a class,HttpExceptionFilter, that implementsExceptionFilter. Annotate it with theCatchdecorator to indicate that it handles HttpExceptions:

Next, populate the class with this code:

This code block retrieves the request and response objects from the ArgumentsHost object and extracts relevant information from the exception. It returns a structured JSON object response, with details about the error, to the client.

Binding Exception Filters

You can bind an exception filter to a controller or your entire application, depending on your needs.

To bind an exception filter globally, first import the exception filter into yourmain.tsfile. Then, pass an instance of your exception filter to theapp.useGlobalFiltersmethod:

To bind an exception to a controller, import theUseFiltersdecorator and your exception filter. Annotate your controller class with the@UseFiltersdecorator and pass an instance of your exception filter as an argument to the decorator:

Where you bind your filter will determine the scope of your error handling. Controller-bound filters will only cater to the controller you bound it to, and application-bound filters will cater to the entire application.

Using Built-In Exceptions to Throw Errors

Nest.js provides built-in exception classes you can use to throw errors.

For example, you can throw 404status code errorswith theNotFoundExceptionclass:

This code block usesa conditional statementto check if the given user exists. If not, it throws a 404 error using theNotFoundException, passing a message as an argument.

Common Built-In Exception Classes

Other built-in exception classes include, but are not limited to, the following.

Best Practices for Error Handling in Nest.js

When handling errors in Nest.js, be sure to use exception filters to catch and handle exceptions globally or per-controller. You can also create custom filters for specific exception types.

Additionally, ensure you use the appropriate built-in exception classes to throw proper and meaningful errors. These practices can significantly improve the reliability of your Nest.js apps.