码迷,mamicode.com
首页 > 其他好文 > 详细

koa 异常处理

时间:2019-12-10 16:56:46      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:exports   code   auth   async   require   异常   const   timeout   ports   

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 异常处理

标签:exports   code   auth   async   require   异常   const   timeout   ports   

原文地址:https://www.cnblogs.com/changyaoself/p/12017270.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!