2017-08-29 98 views
0

我不太明白如何捕捉我扔的地方深我的路线里面的错误,例如:Nodejs - 如何捕获抛出的错误并将其格式化?

// put 
router.put('/', async (ctx, next) => { 
    let body = ctx.request.body || {} 
    if (body._id === undefined) { 
    // Throw the error. 
    ctx.throw(400, '_id is required.') 
    } 
}) 

我会得到不提供_id时:

_id is required. 

但我不不会像纯文本那样抛出。我宁愿在顶级抓住它,然后格式化,例如:

{ 
    status: 400. 
    message: '_id is required.' 
} 

按照doc

app.use(async (ctx, next) => { 
    try { 
     await next() 
    } catch (err) { 
     ctx.status = err.status || 500 

     console.log(ctx.status) 
     ctx.body = err.message 

     ctx.app.emit('error', err, ctx) 
    } 
    }) 

但即使没有尝试在我的中间件抓,我仍然得到_id is required.

任何想法?

回答

1

抛出一个错误,与所需的状态代码:

ctx.throw(400, '_id is required.'); 

并使用default error handler格式化错误响应:

app.use(async (ctx, next) => { 
    try { 
    await next(); 
    } catch (err) { 
    ctx.status = err.statusCode || err.status || 500; 
    ctx.body = { 
     status: ctx.status, 
     message: err.message 
    }; 
    } 
}); 
+0

感谢。 'ctx.throw(400,'_id是必需的。')'正是我所做的。我可能在其他地方做错了事! – laukok

+1

很高兴我的回答很有帮助,问题在于默认错误处理程序中,您为'ctx.body'而不是对象'{status,message}'分配了一个字符串。 – alexmac

+0

好抓!谢谢 :-) – laukok

相关问题