nestjs从零到一,快速上手(五)---- nestjs异常过滤器

发布时间:2024年01月24日

一、异常过滤器配合日志打印 ("@nestjs/common": "^10.0.0",)

1.新建文件?httpExceptionFilter.ts

import {
  ArgumentsHost,
  Catch,
  HttpException,
  LoggerService,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter {
  constructor(private logger: LoggerService) {}
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status = exception.getStatus();
    // console.log('exception', exception);
    // console.log('HttpException', exception);
    this.logger.error(
      exception.message,
      exception.stack,
      new Date().toISOString(),
    );
    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: exception.message || HttpException.name,
    });
  }
}

2.man.ts 引入

import { HttpExceptionFilter } from './filters/httpExceptionFilter'; 
  const logger = WinstonModule.createLogger({ instance });
  app.useGlobalFilters(new HttpExceptionFilter(logger));

二、全局异常捕获配置(代码格式目录等参考上面)获取ip地址的库:request-ip

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

import * as requestIp from 'request-ip';
import { HttpAdapterHost } from '@nestjs/core';

@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  constructor(
    private readonly logger: LoggerService,
    private readonly adapterHost: HttpAdapterHost,
  ) {}
  catch(exception: unknown, host: ArgumentsHost) {
    const { httpAdapter } = this.adapterHost;
    const ctx = host.switchToHttp();
    const request = ctx.getRequest();
    const response = ctx.getResponse();

    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const responseBody = {
      headers: request.headers,
      query: request.query,
      body: request.body,
      params: request.params,
      timestamp: new Date().toISOString(),
      // 还可以加入一些用户信息
      // IP信息
      ip: requestIp.getClientIp(request),
      exceptioin: exception['name'],
      error: exception['response'] || 'Internal Server Error',
    };

    this.logger.error('[toimc]', responseBody);
    httpAdapter.reply(response, responseBody, httpStatus);
  }
}

文章来源:https://blog.csdn.net/ben_grf/article/details/135770850
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。