英文:
Strapi controller throwing a NotFoundError : I get a response status 500 instead 404... How can I fix it?
问题
我有一个Strapi控制器方法,会触发一个NotFoundError:
async matchTrack(ctx) {
throw new NotFoundError('YO NOT FOUND');
}
当我调用这个端点时,会抛出错误,但响应代码是500,而不是404。
[2023-06-08 16:05:39.333] error: YO NOT FOUND NotFoundError: YO NOT FOUND
at Object.matchTrack
我该如何修复这个问题?
英文:
I have a Strapi controller method that fires a NotFoundError:
async matchTrack(ctx) {
throw new NotFoundError('YO NOT FOUND');
}
When I call the endpoint, the error is thrown, but the response code is 500 instead of 404.
> [2023-06-08 16:05:39.333] error: YO NOT FOUND NotFoundError: YO NOT FOUND
> at Object.matchTrack
How can I fix this ?
答案1
得分: 1
尝试这样写 return ctx.badRequest('YO NOT FOUND');
英文:
try this return ctx.badRequest('YO NOT FOUND');
答案2
得分: 1
受到 @darwin-facsts 答案的启发,以下是处理此问题的方法。
上下文错误方法的列表在此处(应使用小驼峰命名法)
//控制器方法
async matchTrack(ctx){
const body = ctx.request.body;
try{
//...服务方法...
} catch (error) {
if (error instanceof NotFoundError) {
return ctx.notFound(error.message,error.details)
}
throw(error);
}
}
英文:
Inspired by @darwin-facsts answer, here's how to handle this.
List of context error methods here (should be lower camel-case)
//controller method
async matchTrack(ctx){
const body = ctx.request.body;
try{
//...service method...
} catch (error) {
if (error instanceof NotFoundError) {
return ctx.notFound(error.message,error.details)
}
throw(error);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论