Exception Filters

With Nest you can move exception handling logic to special classes called Exception Filters.

How it works?

Let's take a look at the following code:

@Get('/:id')
public async getUser(@Response() res, @Param('id') id) {
    const user = await this.usersService.getUser(id);
    res.status(HttpStatus.OK).json(user);
}

Imagine that usersService.getUser(id) method could throws UserNotFoundException.

What's now? We have to catch an exception in route handler:

@Get('/:id')
public async getUser(@Response() res, @Param('id') id) {
    try {
        const user = await this.usersService.getUser(id);
        res.status(HttpStatus.OK).json(user);
    }
    catch(exception) {
        res.status(HttpStatus.NOT_FOUND).send();
    }
}

To sum up, we have to add try...catch blocks to each route handler, where an exception may occur. Is there another way? Yes - Exception Filters.

Let's create NotFoundExceptionFilter:

import { Catch, ExceptionFilter, HttpStatus } from '@nestjs/common';

export class UserNotFoundException {}
export class OrderNotFoundException {}

@Catch(UserNotFoundException, OrderNotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
    public catch(exception, response) {
        response.status(HttpStatus.NOT_FOUND).send();
    }
}

Now, we only have to tell our method to use this filter:

@Get('/:id')
@UseFilters(new CustomExceptionFilter())
public async getUser(@Res() res: Response, @Param('id') id: string) {
    const user = await this.usersService.getUser(id);
    res.status(HttpStatus.OK).json(user);
}

So if usersService.getUser(id) throws UserNotFoundException, NotFoundExceptionFilter will catch it.

Scope

The exception filters can be method-scoped, controller-scoped and global-scoped. There are no contraindications to set-up exception filter to each route handler in the Controller:

@UseFilters(new CustomExceptionFilter())
export class UsersController {}

Or even to set-up it globally:

const app = NestFactory.create(ApplicationModule);
app.useGlobalFilters(new CustomExceptionFilter());

The global exception filters work well with global pipes feature.

results matching ""

    No results matching ""