koa 异常处理

const errCode={
    success:10001,
    badRequest:40000,
    notFound:40004,
    unauthorized:40001,
    forbidden:40003,
    serverErr:50000,
    methodErr:40005,
    reqeustTimeout:40008
};
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.serverErr, 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);

猜你喜欢

转载自www.cnblogs.com/changyaoself/p/12017270.html
koa