我正在使用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不是
所谓的ExceptionFilterExceptionFilter



docs

尝试将exmaple注入(inject)到自定义HttpException中时,您提供了exmaple。但这是错误的。您的异常(exception)不必负责日志记录。多数民众赞成在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/

    10-11 08:40