# 异常捕获
定义一些HttpException
类(自定义错误):
class HttpException extends Error{
constructor(msg = '服务器异常', errorCode = 1000, status = 500) {
super()
this.errorCode = errorCode
this.status = status
this.msg = msg
}
}
class ParamterException extends HttpException{
constructor(msg, errorCode) {
super()
this.status = 400
this.msg = msg || '参数错误'
this.errorCode = errorCode || 1000
}
}
// 上传错误
class UploadException extends HttpException{
constructor(status, msg, errorCode) {
super()
this.status = status || 400
this.msg = msg || '上传错误'
this.errorCode = errorCode || 1000
}
}
定义一个catchError
函数:
const { HttpException } = require("../core/http-exception");
const isDev = process.env.NODE_ENV !== "production";
const catchError = async (ctx, next) => {
try {
await next();
} catch (error) {
const isHttpException = error instanceof HttpException;
// 自定义错误
if (isHttpException) {
ctx.body = {
msg: error.msg,
error_code: error.errorCode,
request: ctx.method + " " + ctx.path,
};
ctx.status = error.status;
return
}
// 开发环境 + 非自定义的错误,抛出错误
if (isDev) {
throw error;
}
// 线上环境 + 非自定义的错误
ctx.body = {
msg: "服务器错误",
error_code: 9999,
request: ctx.method + " " + ctx.path,
};
ctx.status = 500;
}
};
module.exports = catchError;
如何使用:
const app = new Koa()
app.use(catchError) // 在最顶部捕获
← koa解决跨域的方法 path →