/* * @Author:尹鹏孝 * @Date: 2021-08-31 13:28:48 * @LastEditTime: 2021-09-03 08:14:57 * @LastEditors: Please set LastEditors * @Description: 捕获异常生成返回的接口 * @FilePath: \koa2-test-api\src\middlewares\exception.js */ const catchError = async (ctx, next) => { try { await next(); } catch (error) { if (error.errorCode) { ctx.body = { msg: error.msg, errorCode: error.errorCode, request: `${ctx.method} ${ctx.path}` } } else { //对于未知的异常,采用特别处理 console.log(error.originalError); if (error.originalError == 'JsonWebTokenError: invalid token') { error.errorCode = 401; ctx.body = { errorCode: error.errorCode, msg: 'token解析失效,请重新登录', }; } else if (error.originalError == 'TokenExpiredError: jwt expired') { error.errorCode = 401; ctx.body = { errorCode: error.errorCode, msg: 'token失效,请重新登录', }; } else { ctx.body = { msg: '未知异常,请联系管理员010-99999999', }; } } } } module.exports = catchError