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));
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);
}
}