在写接口时,返回json格式且易读的错误提示是有必要的,koa-json-error中间件帮我们做到了
npm i koa-json-error -S
const error = require('koa-json-error')`
app.use(error({
postFormat: (e, { stack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
}))
错误会默认抛出堆栈信息,在生产环境中,没必要返回给用户,在开发环境显示即可
// code
ctx.throw(412, '先决条件失败:id大于数据长度')
返回错误信息
{
"message":"先决条件失败:id大于数据长度",
"name":"PreconditionFailedError",
"status":412
}
模拟出错代码
a.b
{
"name": "ReferenceError",
"message": "a is not defined",
"status": 500
}
请求无响应的url
堆栈示例
{
"stack":"NotFoundError: Not Found
at Object.throw (/Users/zj/code/koa-restful/node_modules/koa/lib/context.js:97:11)
at next.then (/Users/zj/code/koa-restful/node_modules/koa-json-error/lib/middleware.js:52:58)
at process._tickCallback (internal/process/next_tick.js:68:7)",
"message":"Not Found",
"name":"NotFoundError",
"status":404
}