0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Koa.jsのエラーハンドリングで404の場合の対応方法

Last updated at Posted at 2019-03-10

expressよりいい感じらしいので、Koa.jsを使っています。

「さて、エラーハンドリングはどうするんだ~」と思い、公式のwikiがあるじゃないかと喜び、そして、404が一向にキャッチされなくて困りました。キャッチされないくせに、404とだけ文字列で表示されるという。

404の場合は、catchには入ってこない

koa-routerも併用していたので、そっちでハンドリングしなきゃいけないのかなと考えて、解決策を探していたところ、見つけました。普通に、デフォルトのエラーハンドラーが404をハンドリングしないため、try内で自分で`emit`する必要があるようです。

// error handling

app.use(async (ctx, next) => {
  try {
    await next();
    if (ctx.status === 404) {
      ctx.app.emit("error", ctx, {status: 404, message: "u f**ked up"})
    }
  } catch (err) {
    console.log('error', err)
    ctx.status = err.status || 500;
    ctx.body = err.message;
    ctx.app.emit("error", ctx, err);
  }
});

app.on("error", (ctx, err) => {
  console.log("🚧 Error!🚨Error!🚨Error!🚨 🚧");
  ctx.redirect("/error");
});

🚧 Error!🚨Error!🚨Error!🚨 🚧

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?