Strapi controller throwing a NotFoundError : I get a response status 500 instead 404… How can I fix it?

huangapple go评论62阅读模式
英文:

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);
  }

}

huangapple
  • 本文由 发表于 2023年6月8日 22:07:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定