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

标签 node.js nest nestjs

我正在使用 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/

    相关文章:

    html - socket.io 客户端到客户端消息传递

    ElasticSearch 批量索引

    elasticsearch - 通过NEST进行Elasticsearch:连接到多个主机集群的推荐方法是什么

    angular - 如何在 Nx monorepo 中为 NestJS 和 Angular 之间共享的 API 接口(interface)启用 Swagger?

    postgresql - 无法将 SSL 安全数据库连接到 typeorm

    node.js - 在 npm 脚本中将 shell 环境变量作为参数传递

    javascript - 使用 promise - 在失败处理程序中记录堆栈跟踪

    node.js - Homebrew:在 node@8 旁边安装最新的 npm 版本

    c# - 如何在Elasticsearch上使用NEST进行的查询中访问脚本字段?

    javascript - Nest 无法解析导入 JwtService 的服务的依赖关系