Flask-Restful taking over exception handling from Flask during non debug mode

与世无争的帅哥 提交于 2019-12-10 14:59:23

问题


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

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).

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?

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...


回答1:


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)

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.



来源:https://stackoverflow.com/questions/36076650/flask-restful-taking-over-exception-handling-from-flask-during-non-debug-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!