NestJS简明教程——异常处理和日志

一、异常处理

1.1 配置

一般使用拦截器(filter)

bash 复制代码
nest g filter db-exception

./db-exception.filter.ts

ts 复制代码
import { DriverException, NotFoundError } from '@mikro-orm/core';
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';

const DB_HTTP_MAP: Record<string, { status: number; message: string }> = {
  NotFoundError: {
    status: HttpStatus.NOT_FOUND,
    message: 'Resource not found',
  },
};

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

    const mapped = DB_HTTP_MAP[exception.name] ?? {
      status: HttpStatus.INTERNAL_SERVER_ERROR,
      message: 'Database error',
    };

    response.status(mapped.status).json(mapped);
  }
}

2.2 注册

一般使用全局注册

./main.ts

ts 复制代码
import { DbExceptionFilter } from './filter/db-exception/db-exception.filter';
// 加入全局数据库异常过滤器
  app.useGlobalFilters(new DbExceptionFilter());

二、日志

2.1 通过中间件

ts 复制代码
import { Injectable, NestMiddleware } from "@nestjs/common";
import { Request, Response, NextFunction } from "express";

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log("Request ... ");
    next();
  }
}

2.2 通过pino

安装

bash 复制代码
pnpm add pino nestjs-pino pino-http pino-pretty

配置

./main.ts

ts 复制代码
import { Logger } from 'nestjs-pino';
app.useLogger(app.get(Logger));

./app.module.ts

ts 复制代码
import { Module } from '@nestjs/common';
import mikroConfig from '../mikro-orm.config';
import { LoggerModule } from 'nestjs-pino';
@Module({
  imports: [
    LoggerModule.forRoot({
      pinoHttp: {
        transport: {
          targets: [
            {
              target: 'pino-pretty',
              options: {
                colorize: true,
              },
            },
            {
              target: 'pino/file',
              options: {
                destination: './logs/app.log',
                mkdir: true,
              },
            },
          ],
        },
      },
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
相关推荐
Linux_cy14 小时前
服务器管理工具哪个好用?我用了七八个
运维·服务器·javascript·python·ssh·面板·gmssh
变与不变80615 小时前
jQuery细节以及使用应用场景
前端·javascript·jquery
এ慕ོ冬℘゜21 小时前
ES Promise.all/ Promise.race
前端·javascript·elasticsearch
只睡四小时1 天前
端侧推理:face-api.js 首屏 92% 是白下载的
开发语言·javascript·人脸识别·ecmascript·tensorflow.js·face-api.js·端侧推理
用户83134859306981 天前
Vue3 v-for:常用用法与开发高频坑点
前端·javascript·vue.js
Funlang1 天前
fun-ui 开源:把浏览器界面接回来
前端·javascript
2603_965896621 天前
CSS BEM 命名规范|组件化样式分层权威指南
前端·javascript·css
忆挽篱笙歌1 天前
进程替换函数与shenll命令行解释器
前端·javascript·算法
小冯不疯1 天前
688 / 拼多多 / 淘特三类供货链路:从采购单到应付凭证的 4 段对账
javascript
moshuying1 天前
DeppInfer系列之 - 矩阵、注意力与 GPU:拆解 DeepGEMM 与 FlashMLA
前端·javascript·面试