koa 异常处理

Posted changyaoself

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了koa 异常处理相关的知识,希望对你有一定的参考价值。

const errCode={
success:10001,
badRequest:40000,
notFound:40004,
unauthorized:40001,
forbidden:40003,
serverErr:50000,
methodErr:40005,
reqeustTimeout:40008,
unkonwErr:99999
};
const api = {
success:200,
badRequest:400,
notFound:404,
unauthorized:401,
forbidden:403,
serverErr:500,
methodErr:405,
reqeustTimeout:408
};
const success = (ctx,data)=>{
ctx.status = 200;
let body = {
code:10001,
msg:‘成功‘
};
if(data) body.data= data;
ctx.body=body;
};
class HttpException extends Error{
constructor(status,msg,code){
super();
switch (status){
case api.badRequest:
msg = msg || ‘params error‘;
code = code || errCode.badRequest;
break;
case api.unauthorized:
msg = msg || ‘unauthorized‘;
code = code || errCode.unauthorized;
break;
case api.forbidden:
msg = msg || ‘user forbidden‘;
code = code || errCode.forbidden;
break;
case api.notFound:
msg = msg || ‘not found‘;
code = code || errCode.notFound;
break;
case api.serverErr:
msg = msg || ‘server error‘;
code = code || errCode.serverErr;
break;
case api.methodErr:
msg = msg || ‘request method not support‘;
code = code || errCode.methodErr;
break;
case api.reqeustTimeout:
msg = msg || ‘request timeout‘;
code = code || errCode.reqeustTimeout;
break;
default:
status =status || 500;
msg = msg || ‘server error‘;
code = code || errCode.serverErr;

}
this.status = status;
this.msg = msg;
this.code = code;
}
}
//全局错误拦截处理
const catchErr= async (ctx,next)=>{
try {
await next();
}catch (err){
if(err instanceof HttpException){
const {status,code,msg } = err;
ctx.body = {code, msg};
ctx.status = status;
}else {
ctx.body = {code:errCode.unkonwErr, msg:"未知错误"};
ctx.status = api.serverErr;
}
}
};
module.exports={
success,
catchErr,
HttpException
};

 

const koa = require("koa");
const httpUtil = require("./httpUtil");
const app = new koa();
app.use(httpUtil.catchErr);
app.use(async (ctx,next)=>{
    throw new httpUtil.HttpException();
});
app.listen(3000);

 

以上是关于koa 异常处理的主要内容,如果未能解决你的问题,请参考以下文章

KOA学习笔记

全栈项目|小书架|服务器开发-Koa2 全局异常处理

学习koa开发API--- 对异常和参数的处理

异常和TCP通讯

玩转Koa -- 核心原理分析

深入解析Koa之核心原理