Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 935
cytrinox Avatar asked Dec 20 '15 21:12

cytrinox


2 Answers

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, '')
like image 128
Marc Garcia Avatar answered Sep 30 '22 08:09

Marc Garcia


There is a better solution here.

    def custom_response_handler(req, resp, ex, params):
        resp.status = falcon.HTTP_404
        resp.text = "custom text response"

    app = falcon.App()
    app.add_error_handler(HTTPRouteNotFound, custom_response_handler)
like image 41
hleb.albau Avatar answered Sep 30 '22 07:09

hleb.albau