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 @   C羽言  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示