Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to respond with HTTP 500 on any unhandled exception in Falcon framework

Is there a way in Falcon framework to respond with HTTP 500 status on any unspecific exception that is not handled in resource handler? I've tried to add following handler for Exception:

api.add_error_handler(Exception, 
                      handler=lambda e, 
                      *_: exec('raise falcon.HTTPInternalServerError("Internal Server Error", "Some error")'))

But this makes impossible to throw, for example, falcon.HTTPNotFound — it is handled by the handler above and I receive 500 instead of 404.

like image 340
Anton Patiev Avatar asked Sep 19 '16 10:09

Anton Patiev


2 Answers

Yes, it is possible. You need to define a generic error handler, check if the exception is instance of any falcon error, and if it is not, then raise your HTTP_500.

This example shows a way of doing it.

def generic_error_handler(ex, req, resp, params):
    if not isinstance(ex, HTTPError):
        raise HTTPInternalServerError("Internal Server Error", "Some error")
    else:  # reraise :ex otherwise it will gobble actual HTTPError returned from the application code ref. https://stackoverflow.com/a/60606760/248616
        raise ex

app = falcon.API()
app.add_error_handler(Exception, generic_error_handler)
like image 162
Jav_Rock Avatar answered Sep 20 '22 18:09

Jav_Rock


Accepted answer seems to gobble actual HTTPError returned from the application code. This is what worked for me:

def generic_error_handler(ex, req, resp, params):
    if not isinstance(ex, HTTPError):
        logger.exception("Internal server error")
        raise HTTPInternalServerError("Internal Server Error")
    else:
        raise ex

like image 33
Oleg Avatar answered Sep 20 '22 18:09

Oleg