Override Falcon's default error handler when no route matches
Asked Answered
D

2

6

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.

Desiderative answered 20/12, 2015 at 21:32 Comment(0)
A
5

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, '')
Appanage answered 21/12, 2015 at 12:6 Comment(0)
B
2

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)
Brotherson answered 22/4, 2021 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.