-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add koa-error & koa-api-error-response middleware
- Loading branch information
1 parent
0868fa6
commit 69d6c67
Showing
4 changed files
with
61 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { Context } from 'koa'; | ||
import { apiServerInstance } from '../services'; | ||
|
||
/** | ||
* 处理自定义接口错误,并响应错误信息 | ||
*/ | ||
const koaError = async function (ctx: Context, next) { | ||
try { | ||
await next(); | ||
} catch (_err) { | ||
const err = _err || new Error('Null or undefined error'); | ||
// 判断是否为通用 api error | ||
if (apiServerInstance.isApiErrorResponse(err.message)) { | ||
ctx.body = JSON.parse(err.message); | ||
return; | ||
} | ||
throw (err); | ||
} | ||
}; | ||
|
||
export default koaError; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { Context } from 'koa'; | ||
import GLOBAL_CONFIG from '../config/system.config'; | ||
/** | ||
* 异常处理 | ||
*/ | ||
const koaError = async function (ctx: Context, next) { | ||
try { | ||
await next(); | ||
} catch (_err) { | ||
const err = _err || new Error('Null or undefined error'); | ||
ctx.app.emit('error', err, ctx); | ||
ctx.set('Cache-Control', 'no-cache, max-age=0'); | ||
ctx.status = err.status || 500; | ||
ctx.type = 'application/json'; | ||
const resp = err.response || {}; | ||
ctx.body = { | ||
code: err.code, | ||
error: resp.body || err.error, | ||
message: err.message, | ||
}; | ||
// 在开发环境下,显示错误堆栈信息 | ||
if (GLOBAL_CONFIG.isDev) { | ||
ctx.body.stack = err.stack; | ||
} | ||
} | ||
}; | ||
|
||
export default koaError; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters