Skip to content

Allow error handler to pass on decision to subsequent handlers #2197

Closed

Description

@mtvx

I would like to do error handling conditionally, like:

def internal_error(exc: peewee.InternalError) -> Optional[Response]:
    if exc.args[0] == 1213:
        # Deadlock found when trying to get lock; try restarting transaction
        return CustomErrorResponse(...)

def any_exception(exc: Exception) -> Response:
        return CustomErrorResponse(...)

app.register_error_handler(peewee.InternalError, internal_error)
app.register_error_handler(Exception, any_exception)

Could it be so that if None is returned from an errorhandler, Flask keeps on iterating and calls the next suitable errorhandler?

Lines: https://github.com/pallets/flask/blob/master/flask/app.py#L1521-L1525 Looks like the code has changed somewhat since 0.10.1 that I'm running (in 0.10.1 this would have been 3-line change I think).

Of course I could call return any_exception(exc) from internal_error() but that kinda adds direct dependency between the two methods and I would like to avoid it (consider the error handlers coming from different modules/classes etc. and maybe there's even third error handler sitting between that would be skipped here).

Activity

  1. davidism commented on May 30, 2017

    @davidism
    Member

    This is similar to how before_request handlers can return a response if they want to stop response handling early. I started to implement this, but I've decided to close it.

    Error handler behavior is already somewhat complicated due to the lookup by blueprint, app, code, and exception, all over the exception's MRO. The current order is:

    1. blueprint, code, mro
    2. app, code, mro
    3. blueprint, exception, mro
    4. app, exception, mro

    When you throw in the idea of falling through handlers, it becomes even worse: what order is something handled in if there are handlers spread across multiple maps? For example, if the following handlers exist:

    1. blueprint, Child(Parent(Exception)), doesn't return
    2. blueprint, Exception, returns
    3. app, Parent, returns

    Should the next handler for Child be 2 because it is the next closest base in the current map, or should it be 3 because it is the next most specific base? What if 3 didn't return, how would we get back to 2? What if there were more layers of bases interleaved back and forth between maps?

    So while it was an interesting idea and it makes sense why you'd expect that, the implementation becomes way too hard to reason about.

  2. davidism commented on May 30, 2017

    @davidism
    Member

    Here's the patch if anyone's interested:

    From c7ee054d0ed4c85cdbe80007f4a6ef2eda5457b2 Mon Sep 17 00:00:00 2001
    From: David Lord <[email protected]>
    Date: Tue, 30 May 2017 12:26:28 -0700
    Subject: [PATCH] allow error handlers to return none
    
    ---
     flask/app.py        | 66 +++++++++++++++++++++++++++--------------------------
     tests/test_basic.py | 24 +++++++++++++++++++
     2 files changed, 58 insertions(+), 32 deletions(-)
    
    diff --git a/flask/app.py b/flask/app.py
    index 3c6d9f5..4ccaf5d 100644
    --- a/flask/app.py
    +++ b/flask/app.py
    @@ -1489,31 +1489,24 @@ class Flask(_PackageBoundObject):
             return f
     
         def _find_error_handler(self, e):
    -        """Find a registered error handler for a request in this order:
    -        blueprint handler for a specific code, app handler for a specific code,
    -        blueprint generic HTTPException handler, app generic HTTPException handler,
    -        and returns None if a suitable handler is not found.
    -        """
    -        exc_class, code = self._get_exc_class_and_code(type(e))
    -
    -        def find_handler(handler_map):
    -            if not handler_map:
    -                return
    +        """Iterate over the error handlers that can handle the given error.
    +        They are ordered by specificity: blueprint code; global code;
    +        blueprint exception; global exception. Each class in the MRO is tried
    +        across maps before moving to the next class."""
    +        exc_class, exc_code = self._get_exc_class_and_code(type(e))
    +        handler_maps = [m for m in (
    +            self.error_handler_spec.get(name, {}).get(code) for is_bp, name, code in (
    +                (True, request.blueprint, exc_code), (False, None, exc_code),
    +                (True, request.blueprint, None), (False, None, None)
    +            ) if not (is_bp and name is None)
    +        ) if m]
     
             for cls in exc_class.__mro__:
    +            for handler_map in handler_maps:
                     handler = handler_map.get(cls)
    -                if handler is not None:
    -                    # cache for next time exc_class is raised
    -                    handler_map[exc_class] = handler
    -                    return handler
    -
    -        # check for any in blueprint or app
    -        for name, c in ((request.blueprint, code), (None, code),
    -                        (request.blueprint, None), (None, None)):
    -            handler = find_handler(self.error_handler_spec.get(name, {}).get(c))
     
    -            if handler:
    -                return handler
    +                if handler is not None:
    +                    yield handler
     
         def handle_http_exception(self, e):
             """Handles an HTTP exception.  By default this will invoke the
    @@ -1527,10 +1520,13 @@ class Flask(_PackageBoundObject):
             if e.code is None:
                 return e
     
    -        handler = self._find_error_handler(e)
    -        if handler is None:
    +        for handler in self._find_error_handler(e):
    +            rv = handler(e)
    +
    +            if rv is not None:
    +                return rv
    +
             return e
    -        return handler(e)
     
         def trap_http_exception(self, e):
             """Checks if an HTTP exception should be trapped or not.  By default
    @@ -1595,11 +1591,13 @@ class Flask(_PackageBoundObject):
             if isinstance(e, HTTPException) and not self.trap_http_exception(e):
                 return self.handle_http_exception(e)
     
    -        handler = self._find_error_handler(e)
    +        for handler in self._find_error_handler(e):
    +            rv = handler(e)
    +
    +            if rv is not None:
    +                return rv
     
    -        if handler is None:
             reraise(exc_type, exc_value, tb)
    -        return handler(e)
     
         def handle_exception(self, e):
             """Default exception handling that kicks in when an exception
    @@ -1611,9 +1609,7 @@ class Flask(_PackageBoundObject):
             .. versionadded:: 0.3
             """
             exc_type, exc_value, tb = sys.exc_info()
    -
             got_request_exception.send(self, exception=e)
    -        handler = self._find_error_handler(InternalServerError())
     
             if self.propagate_exceptions:
                 # if we want to repropagate the exception, we can attempt to
    @@ -1626,9 +1622,15 @@ class Flask(_PackageBoundObject):
                     raise e
     
             self.log_exception((exc_type, exc_value, tb))
    -        if handler is None:
    -            return InternalServerError()
    -        return self.finalize_request(handler(e), from_error_handler=True)
    +        internal_error = InternalServerError()
    +
    +        for handler in self._find_error_handler(internal_error):
    +            rv = handler(e)
    +
    +            if rv is not None:
    +                return self.finalize_request(rv, from_error_handler=True)
    +
    +        return internal_error
     
         def log_exception(self, exc_info):
             """Logs an exception.  This is called by :meth:`handle_exception`
    diff --git a/tests/test_basic.py b/tests/test_basic.py
    index c494e8b..d46ef3d 100644
    --- a/tests/test_basic.py
    +++ b/tests/test_basic.py
    @@ -870,6 +870,30 @@ def test_error_handling(app, client):
         assert b'forbidden' == rv.data
     
     
    +def test_error_handler_returns_none(app, client):
    +    class Low(Exception):
    +        pass
    +
    +    class High(Low):
    +        pass
    +
    +    @app.errorhandler(High)
    +    def handle_high(e):
    +        pass
    +
    +    @app.errorhandler(Low)
    +    def handle_low(e):
    +        return 'low', 200
    +
    +    @app.route('/')
    +    def index():
    +        raise High()
    +
    +    rv = client.get('/')
    +    assert rv.status_code == 200
    +    assert rv.data == b'low'
    +
    +
     def test_error_handling_processing(app, client):
         app.config['LOGGER_HANDLER_POLICY'] = 'never'
         app.testing = False
    -- 
    2.13.0
    
    
  3. mtvx commented on May 31, 2017

    @mtvx
    Author

    Alright, thanks for looking into it!

    While I don't understand all that you wrote, I was in the assumption that error handlers are looked up in the order of declaration. In that scenario, just keeping iterating to the next handler should be easy. But apparently (newer) versions of Flask do things differently...

    For anyone else stumbling here, you can probably achieve this by:

    def internal_error(exc: peewee.InternalError) -> Response:
        if exc.args[0] == 1213:
            return CustomErrorResponse(...)
        return any_exception(exc)  # <-- this
    
    def any_exception(exc: Exception) -> Response:
            return CustomErrorResponse(...)

    As stated, it's not perfect, but probably suffices.

  4. davidism commented on May 31, 2017

    @davidism
    Member

    They are not looked up in the order you assumed.

  5. mtvx commented on May 31, 2017

    @mtvx
    Author

    I need to RTFM then... thanks!

  6. locked as resolved and limited conversation to collaborators on Nov 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions