23 lines
700 B
JavaScript
23 lines
700 B
JavaScript
|
|
import * as log4js from '../../log4js.js'
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 统一错误处理中间件
|
|||
|
|
* 捕获所有未处理异常,规范化错误响应格式,避免泄露内部错误信息
|
|||
|
|
*/
|
|||
|
|
export default async function errorHandler(ctx, next) {
|
|||
|
|
try {
|
|||
|
|
await next()
|
|||
|
|
} catch (err) {
|
|||
|
|
log4js.koa.error(`[${ctx.method}] ${ctx.path} — ${err.message}`, err.stack || '')
|
|||
|
|
|
|||
|
|
// 已知业务错误(主动 throw new Error)直接返回消息
|
|||
|
|
if (err.status) {
|
|||
|
|
ctx.status = err.status
|
|||
|
|
ctx.body = { code: err.status, message: err.message || '请求错误' }
|
|||
|
|
} else {
|
|||
|
|
ctx.status = 500
|
|||
|
|
ctx.body = { code: 500, message: '服务器内部错误,请稍后再试!' }
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|