一、异常处理
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 {}