Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 739
orange Avatar asked Mar 18 '16 05:03

orange


1 Answers

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.

like image 103
zwirbeltier Avatar answered Sep 22 '22 16:09

zwirbeltier