根据 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 对象与我从模型中引发的自定义异常不同。无法为此找出任何解决方案。关于解决这个问题的任何想法或我可以遵循的任何不同方法??
序列化异常的最简单方法是将其转换为字符串
str(err)