zoukankan      html  css  js  c++  java
  • 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)
        }
    );
    
  • 相关阅读:
    初始mysql语句
    MySQL 数据库 的安装和基本管理
    POJ 3685
    总结-LCT
    $亲属关系$
    一:包装好和吹出去 二:三国心得
    创业心得
    阿里前CEO卫哲的万字长文:被马云骂醒,看透B2B 10大核心问题!
    英雄不问出处, 看看商界大佬年轻时受过的苦
    最应该富养的,不是孩子是妻子!
  • 原文地址:https://www.cnblogs.com/xujunkai/p/12900077.html
Copyright © 2011-2022 走看看