I recently practiced koa, there are two needs.
- The content returned by the interface remains uniform
- I don't want to process ctx.body for the interface code, I want to return when I get the result, and throw when there is an error.
So I wrote a middleware, the code is like this.
const ApiRouter = () => async (ctx, next) => {
try {
const data = await next()
ctx.body = {
success:true,
data,
}
} catch (error) {
ctx.body = {
success:false,
message:error.message,
}
}
}
const api = new Router()
api.use(ApiRouter())
// 路由的定义还是跟原来一样
// 区别就是,你不需要用到ctx参数了
// 如果一切正常,你直接return
// 如果出现错误,你就抛一个错
api.get('/test', () => {
if (Math.random() > 0.5) return 'Hello World!'
else throw new Error('Goodbye World!')
})
// 应用路由
// 建议放到单独的路径下面
router.use('/api', api.routes(), api.allowedMethods());
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。