Koa 应用中使用错误处理中间件

示例:如果访问应用时 URL 中包含参数 error=true,则会抛出一个错误。错误处理中间件会捕获这个错误,并返回适当的错误响应。

const Koa = require('koa');
const app = new Koa();

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    // 执行下一个中间件
    await next();
  } catch (err) {
    // 在这里处理错误
    console.error('Error:', err);
    ctx.status = err.status || 500;
    ctx.body = {
      error: {
        message: err.message || 'Internal Server Error'
      }
    };
  }
});

// 示例路由处理
app.use(async (ctx) => {
  // 如果 URL 中包含了参数 "error=true",则抛出一个错误
  if (ctx.query.error === 'true') {
    throw new Error('Oops! Something went wrong.');
  } else {
    ctx.body = 'Hello, world!';
  }
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

 

posted @ 2024-04-08 11:48  C羽言  阅读(42)  评论(0)    收藏  举报