Trọ*_*ông 6 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 {}
Run Code Online (Sandbox Code Playgroud)
它工作得很好。
import {Logger} from './logger.service';
export class UserService {
constructor(
private logger: Logger
) {}
private test = () => {
this.logger.log("test"); // log success "test" to console
}
}
Run Code Online (Sandbox Code Playgroud)
但是如何将我的自定义 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!
}
}
Run Code Online (Sandbox Code Playgroud)
感谢阅读。
首先你的class ForbiddenException extends HttpException并不是它所说的那样ExceptionFilter。ExceptionFilter是
异常层,负责处理应用程序中所有未处理的异常
当您尝试将 exmaple 注入您的自定义时,您提供了 exmaple HttpException。但那是错误的。您的异常不必负责记录。这才是ExceptionFilter应该负责的。
无论如何,目前(2019 年 10 月 17 日)官方文档中没有示例如何将提供程序注入ExceptionFilter.
您可以将其传递给 constructor init,但您应该在使用app.get<T>(...)方法之前获取 Logger 实例。
例如,我更改了异常过滤器文档中的代码:
// 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,
});
}
}
Run Code Online (Sandbox Code Playgroud)
和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));
Run Code Online (Sandbox Code Playgroud)
该技术可用于所有这些INestApplication方法:
首先,要将依赖注入与异常过滤器一起使用,您不能使用以下useGlobalFilters()方法注册它们:
const app = await NestFactory.create(MainModule, {
logger: false,
});
const logger = app.get<MyLogger>(MyLogger);
app.useLogger(logger);
//Remove this line
//app.useGlobalFilters(new HttpExceptionFilter(logger));
Run Code Online (Sandbox Code Playgroud)
接下来MainModule,在您的 中,将自定义异常过滤器添加为提供程序(注意:无论您将过滤器添加到哪个模块,过滤器都会自动设置为全局,但作为最佳实践,请将它们添加到顶级模块):
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { LoggerModule } from './logger.module';
import { ForbiddenException } from './forbidden.exception.filter.ts';
@Module({
imports: [
LoggerModule //this is your logger module
],
providers: [
{
provide: APP_FILTER, //you have to use this custom provider
useClass: ForbiddenException //this is your custom exception filter
}
]
})
export class MainModule {}
Run Code Online (Sandbox Code Playgroud)
现在您可以将记录器注入到自定义异常过滤器中:
import {HttpException, HttpStatus, Injectable} from '@nestjs/common';
import { Logger } from './path/to/logger';
@Injectable()
export class ForbiddenException extends HttpException {
constructor(private logger: Logger) {}
catch(exception: HttpException, response) {
this.logger.log('test');
}
}
Run Code Online (Sandbox Code Playgroud)
伪代码,但我想你明白了。
| 归档时间: |
|
| 查看次数: |
6040 次 |
| 最近记录: |