Flask-Restful在非调试模式下从Flask接管异常处理 [英] Flask-Restful taking over exception handling from Flask during non debug mode

查看:133
本文介绍了Flask-Restful在非调试模式下从Flask接管异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开发期间使用了Flask的异常处理(@app.errorhander(MyException)),即使对于来自Flask-Restful端点的异常,它也可以正常工作.

I've used Flask's exception handling during development (@app.errorhander(MyException)) which worked fine even for exceptions coming from Flask-Restful endpoints.

但是,我注意到当切换到debug=False时,Flask-Restful会完全接管异常处理(因为propagate_exceptions也是False).我喜欢Flask-Restful会为所有未处理的异常发送内部服务器错误,但是不幸的是,对于具有Flask异常处理程序的对象(当这些异常来自Flask-Restful端点时),也会发生内部服务器错误.

However, I noticed that when switching to debug=False, Flask-Restful is taking over the exception handling entirely (as with this propagate_exceptions is False too). I like that Flask-Restful is sending internal server errors for all unhandled exceptions, but unfortunately this also happens for those that have a Flask exception handler (when these exceptions are coming from a Flask-Restful endpoint).

有没有办法告诉Flask-Restful仅处理Flask错误处理程序无法处理的异常?如果不是,我可以将某些异常类型排除在Flask-Restful的处理之下,而让它们由Flask处理吗?

Is there a way to tell Flask-Restful to only handle exceptions that the Flask error handler wouldn't handle? If not, can I exclude certain exception types from being handled by Flask-Restful, so they get handled by Flask?

我的最后一个选择是重写Flask-Restful的Api.handle_error并自己实现此逻辑,但是我想先使用现有的API ...

My last option is to override Flask-Restful's Api.handle_error and implement this logic myself, but I'd like to use existing APIs first...

推荐答案

简而言之,我的解决方案是创建Api的子类,将其修改为仅处理HTTPException类型的异常.

In short my solution just is to create a sub-class of Api that modifies it to only handle exceptions of type HTTPException.

from flask_restful import Api as _Api
from werkzeug.exceptions import HTTPException

class Api(_Api):
    def error_router(self, original_handler, e):
         """ Override original error_router to only handle HTTPExceptions. """
        if self._has_fr_route() and isinstance(e, HTTPException):
            try:
                return self.handle_error(e)
            except Exception:
                pass  # Fall through to original handler
        return original_handler(e)


也就是说,出于某些原因,我认为首先覆盖app.handle_user_exceptionapp.handle_exception是一个错误的设计决定.


That said, I think overriding app.handle_user_exception and app.handle_exception is a bad design decision in the first place for several reasons.

这篇关于Flask-Restful在非调试模式下从Flask接管异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆