TypeError:类型为CustomException的对象不可JSON序列化

根据flask-restful文档,它会在flask-RESTful路由上发生的任何400或500错误上调用handle_error()函数。因此,我尝试使用此回调在整个应用程序中处理异常,以为它将利用我的应用程序中的多个try catch块。但是,从模型中引发自定义异常(ResourceNotFound)时会引发另一个异常TypeError: Object of type ResourceNotFound is not JSON serializable

from werkzeug.exceptions import HTTPException
from flask_restful import Api
class ExtendedAPI(Api):
    def handle_error(self,err):
        """
        This class overrides 'handle_error' method of 'Api' class,to extend global exception handing functionality of 'flask-restful'
        and helps preventing writing unnecessary
        try/except block though out the application
        """
        # import pdb; pdb.set_trace()
        logger.error(err)
        # Handle HTTPExceptions
        if isinstance(err,HTTPException):
            return jsonify({
                'message': getattr(
                    err,'description',HTTP_STATUS_CODES.get(err.code,'')
                )
            }),err.code
        if isinstance(err,ValidationError):
            resp = {
                'success': False,'errors': err.messages
            }
            return jsonify(resp),400
        # If msg attribute is not set,# consider it as Python core exception and
        # hide sensitive error info from end user
        # if not getattr(err,'message',None):
        #     return jsonify({
        #         'message': 'Server has encountered some error'
        #     }),500
        # Handle application specific custom exceptions
        return jsonify(**err.kwargs),err.http_status_code

自定义例外:

class Error(Exception):
    """Base class for other exceptions"""
    def __init__(self,http_status_code: int,*args,**kwargs):
        # If the key `msg` is provided,provide the msg string
        # to Exception class in order to display
        # the msg while raising the exception
        self.http_status_code = http_status_code
        self.kwargs = kwargs
        msg = kwargs.get('msg',kwargs.get('message'))
        if msg:
            args = (msg,)
            super().__init__(args)
        self.args = list(args)
        for key in kwargs.keys():
            setattr(self,key,kwargs[key])


class ResourceNotFound(Error):
    """Should be raised in case any resource is not found in the DB"""

handle_error函数处理HTTPException,棉花糖验证错误以及处理我的自定义异常的最后一条语句。 但是使用pdb时,我看到handle_error()收到的err对象与我从模型中引发的自定义异常不同。无法为此找到任何解决方案。关于解决此问题的任何想法或我可以采取的任何其他方法?

colin2625 回答:TypeError:类型为CustomException的对象不可JSON序列化

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3128362.html

大家都在问