异常过滤器

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

你可以使用Nest将异常处理逻辑移动到异常过滤器的特殊类中。

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:

想象以下usersService.getUser(id)方法可能抛出一个异常--UserNotFoundException。 那么怎么办呢?我们应该在路由处理器中捕捉该异常。

@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:

总的来说,我们应该为每个可能出现异常路由处理程序添加try...catch快。还有其他方式么?有--我们可以使用异常过滤器。 让我们来创建一个过滤器--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.

所以如果usersService.getUser(id)抛出UserNotFoundException时,可以使用NotFoundExceptionFilter捕捉UserNotFoundException

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:

范围

异常过滤器可以时method-scoped, controller-scopedglobal-scoped的,所以在控制器中为每个路由处理程序设置异常处理过滤器时是没有任何限制的:

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

Or even to set-up it globally:

甚至可以直接将它设置为globally

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

results matching ""

    No results matching ""