import { Provide } from "@midwayjs/decorator";
import {
  IWebMiddleware,
  IMidwayKoaContext,
  IMidwayKoaNext,
} from "@midwayjs/koa";
import ErrNo from "@/constants/errorEnum";

@Provide()
export default class ErrorMiddleware implements IWebMiddleware {
  resolve() {
    return async (ctx: IMidwayKoaContext, next: IMidwayKoaNext) => {
      try {
        await next();
      } catch (err: any) {
        console.log(err);
        const errno = err.errno || ErrNo.ERROR;
        const result = {
          errno,
          message: `${err.message}`,
          data: null,
        };
        ctx.status = 400;
        ctx.body = result;
      }
    };
  }
}
