TMDOG的微服务之路_04——Nest.js 的异常筛选器

TMDOG的微服务之路_04——Nest.js 的异常筛选器

博客地址:TMDOG的博客

在上一篇博客中,我们实现了一个简易的用户管理 API 并添加了中间件功能。本篇博客,我们将探讨如何在 Nest.js 中使用异常筛选器。可以帮助我们更好地处理异常。

异常筛选器

1. 创建异常筛选器

异常筛选器用于捕获和处理应用程序中的HTTP异常。在 src\common\filter 下创建一个异常筛选器 http-exception.filter.ts

import {
    ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import {
    Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
   
  catch(exception: HttpException, host: ArgumentsHost) {
   
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>

你可能感兴趣的:(微服务,javascript,架构)