gpt4 book ai didi

exception-handling - NestJs - 从异常过滤器发送响应

转载 作者:行者123 更新时间:2023-12-01 12:12:16 24 4
gpt4 key购买 nike

我试图实现一个简单的行为:每当抛出异常时,我想将错误作为响应发送。我的那种天真的代码看起来像这样,但根本没有响应:

异常过滤器:

import { ExceptionFilter, ArgumentsHost, Catch } from '@nestjs/common';

@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
return JSON.stringify(
{
error: exception,
},
null,
4,
);
}
}

模块

@Module({
imports: [],
controllers: [AppController, TestController],
providers: [AppService, AnyExceptionFilter],
})
export class AppModule {}

main.ts

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new AnyExceptionFilter());
await app.listen(1212);
}
bootstrap();

有什么我想念的吗?提前致谢 :)

最佳答案

import { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';

@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
catch(error: Error, host: ArgumentsHost) {

const response = host.switchToHttp().getResponse();

const status = (error instanceof HttpException) ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

response
.status(status)
.json(error);
}
}

这段代码对我来说似乎工作正常。

嵌套版本:5.0.1

关于exception-handling - NestJs - 从异常过滤器发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50831216/

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