gpt4 book ai didi

node.js - NestJS 如何将自定义 Logger 添加到自定义 ExceptionFilter

转载 作者:行者123 更新时间:2023-12-01 05:51:40 27 4
gpt4 key购买 nike

我正在使用 NestJS 5.4.0
我有自定义 LoggerService,它运行良好。但是,如何将此 LoggerService 添加到 ExceptionFilter。

// logger.service.ts
import {Injectable, LoggerService} from '@nestjs/common';
@Injectable()
export class Logger implements LoggerService {
log(message: string) {
console.log(message);
}
error(message: string, trace: string) {
console.error(message);
}
warn(message: string) {
console.warn(message);
}
}

//logger.module.ts
import { Module } from '@nestjs/common';
import {Logger} from '../services/logger.service';
@Module({
providers: [Logger],
exports: [Logger],
})
export class LoggerModule {}


// user.module.ts
import { Module } from '@nestjs/common';
import {UserService} from '../services/user.service';
import {LoggerModule} from './logger.module';

@Module({
imports: [LoggerModule],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}

它运行良好。
import {Logger} from './logger.service';
export class UserService {
constructor(
private logger: Logger
) {}
private test = () => {
this.logger.log("test"); // log success "test" to console
}
}

但是如何将我的自定义 Logger 添加到 ExceptionFilter
// forbidden.exception.filter.ts
import {HttpException, HttpStatus, Injectable} from '@nestjs/common';

@Injectable()
export class ForbiddenException extends HttpException {
constructor(message?: string) {
super(message || 'Forbidden', HttpStatus.FORBIDDEN);
// I want to add my custom logger here!
}
}

感谢阅读。

最佳答案

首先你的class ForbiddenException extends HttpException不是
它叫什么ExceptionFilter . ExceptionFilter

exceptions layer which is responsible for processing all unhandled exceptions across an application



docs

当您尝试将其注入(inject)自定义 HttpException 时,您提供了示例.但那是错误的。您的异常不必负责记录。就是这样 ExceptionFilter应该负责。

无论如何,目前(2019 年 10 月 17 日)官方文档中没有示例如何将提供程序注入(inject) ExceptionFilter .

您可以将其传递给 constructor在初始化时,但您应该先使用 app.get<T>(...) 获取 Logger 实例方法。

例如,我从 exception-filters docs 更改了代码:
// HttpExceptionFilter.ts

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

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
constructor(private readonly logger: MyLogger) {}

catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();

if (status >= 500) {
this.logger.error({ request, response });
}

response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}

bootstrap.ts代码:
// bootstrap.ts

const app = await NestFactory.create(MainModule, {
logger: false,
});

const logger = app.get<MyLogger>(MyLogger);
app.useLogger(logger);
app.useGlobalFilters(new HttpExceptionFilter(logger));

此技术可用于所有这些 INestApplication方法:
  • app.useGlobalFilters
  • app.useGlobalGuards
  • app.useGlobalInterceptors
  • app.useGlobalPipes
  • app.useLogger
  • app.useWebSocketAdapter
  • 关于node.js - NestJS 如何将自定义 Logger 添加到自定义 ExceptionFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53394758/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com