pythonfalconframework

Override Falcon's default error handler when no route matches


When Falcon(-Framework) could not find a route for a specific request, 404 is returned. How can I override this default handler? I want to extend the handler with a custom response.


Solution

  • The default handler when no resource matches is the path_not_found responder:

    But as you can see in the _get_responder method of falcon API, it can't be override without some monkey patching.

    As far as I can see, there are two different ways to use a custom handler:

    1. Subclass the API class, and overwrite the _get_responder method so it calls your custom handler
    2. Use a default route that matches any route if none of the application ones are matched. You probably prefer to use a sink instead of a route, so you capture any HTTP method (GET, POST...) with the same function.

    I would recommend the second option, as it looks much neater.

    Your code would look like:

    import falcon
    
    class HomeResource:
        def on_get(self, req, resp):
            resp.body = 'Hello world'
    
    def handle_404(req, resp):
        resp.status = falcon.HTTP_404
        resp.body = 'Not found'
    
    application = falcon.API()
    application.add_route('/', HomeResource())
    # any other route should be placed before the handle_404 one
    application.add_sink(handle_404, '')