异常过滤器
异常过滤器
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-scoped
和 global-scoped
的,所以在控制器中为每个路由处理程序设置异常处理过滤器时是没有任何限制的:
@UseFilters(new CustomExceptionFilter())
export class UsersController {}
Or even to set-up it globally:
甚至可以直接将它设置为globally
。
const app = NestFactory.create(ApplicationModule);
app.useGlobalFilters(new CustomExceptionFilter());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论