I have logger custom module, filter exception catch all error, middleware auth. when I throw error in other module, logger module work ok in filter exception. But when throw error in middleware, this.logger.fatal()
is undefined. Any suggestion please. Thank you
exception.filter.ts
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
constructor(
@Inject(forwardRef(() => LogController))
private readonly logger: LogController) {
}
catch(exception: HttpException | Error, host: ArgumentsHost): void {
const ctx: HttpArgumentsHost = host.switchToHttp();
const response: Response = ctx.getResponse();
const status = exception instanceof HttpException ? exception.getStatus() :
if (status >= 500) {
this.logger.fatal(exception['message'], exception!.stack.toString())
}
if (status >= 400 && status < 500) {
this.logger.error(exception['message'], exception!.stack.toString())
}
// Response to client
AllExceptionsFilter.handleResponse(response, exception)
}
}
auth.middleware.ts
export class AuthenticationMiddleware{
async use(req: Request, res: Response, next: NextFunction) {
throw new HttpException({message: 'Authentication got error', status: 500},500)
}
}
log.service.ts
@Injectable()
export class LogService {
constructor(
) { }
error(message: any, stack?: string) {
console.log(`message::${message} - stack::${stack}`) });
}
fatal(message: any, stack?: string) {
console.log(`message::${message} - stack::${stack}`) }); });
}
}
I suppose you should inject LogService
into AllExceptionsFilter
, not LogController
.
In your main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// resolve LogService
const logService = app.get<LogService>(LogService);
app.useGlobalFilters(new AllExceptionsFilter(logService));
await app.listen(3000);
}
bootstrap();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.