flask-restful结合vue自定义错误类型

flask-restful结合vue自定义错误类型

1.后端代码

  • 自定义异常的基类:
from flask import request
from werkzeug.exceptions import HTTPException
class APIException(HTTPException):
    def __init__(self, code, message):
        self._code = code
        self._message = message

    @property
    def code(self):
        # 返回错误状态码
        return self._code

    @property
    def message(self):
        return self._message

    def __str__(self):
        # 返回错误message
        return self.__class__.__name__ + ': ' + self.message

    # 定义返回的Content-Type类型
    def get_headers(self, environ=None):
        """
        定义我们要返回数据类型为json
        :param environ:
        :return:
        """
        return [("Content-Type", "application/json")]

    @staticmethod
    def get_url_no_param():
        # 返回发生异常的url进行处理,去除 ? 后面的内容
        full_path = str(request.full_path)
        print("full___-path",full_path)
        main_path = full_path.split("?")
        return main_path[0]

  • 自定义异常类
class Forbidden(APIException):
    #, model_name, id
    def __init__(self):
        # .format(model_name.title(), id)
        message = '服务器拒绝执行此请求'
        super(Forbidden, self).__init__(403, message)
class NotFound(APIException):
    def __init__(self):
        message = '服务器无法找到资源'
        super(NotFound, self).__init__(404, message)
  • 视图类定义raise异常。
from flask_restful import Resource, fields, request, marshal, abort
class TestError(Resource):
    def get(self):
        try:
            # 触发自定义异常
            raise Forbidden()
        except APIException as e:
            # 附加任何关键字用于以后处理的HttpResponse异常的参数
            abort(e.code,message=str(e))

2.前端vue代码

  • 发起一个axios请求
async testerror () {
      const data = await this.$http.get("/test_error/");
      if (data.status !== 200) {
		// alert错误
        this.$message.error(data.data.message)
      }
    },
  • 定义响应拦截器:
axios.interceptors.response.use(
    response => {
      if (response.data.status == 10 || response.data.message=='用户未登录') {
          router.push({
              path:"/",
              query: { redirect: router.currentRoute.fullPath }//从哪个页面跳转
          })
      }
      return response
    },
    error => {
      switch (error.response.status) {
          case 404:
              console.log(error.response)
              break;
          case 403:
            console.log(error.response);
            break;
      }
      return error.response
      // return Promise.reject(error)
    }
);

猜你喜欢

转载自www.cnblogs.com/xujunkai/p/12900077.html