Closed samuelerickson977 closed 1 year ago
Because the 404 handler needs to serve both the regular web clients and the api clients. The handler in he main blueprint uses content negotiation headers to serve te correct response to each client.
I see where I was confused. In the book, the Example 14-4 says that this code is in app/api/errors.py
, but really this code is in app/main/errors.py
. So basically, even though the error handler is technically in a different blueprint than api, it will still get called? Is this the best way to do this?
The error handler function is decorated with app_errorhandler
. This means that this is an app-wide error handler. If you had used errorhandler
instead, then it would be limited to the blueprint in which it is defined.
In my experience, using blueprint specific error handlers is more complicated. The 404 example is actually a very good one. How would Flask know which blueprint a not found endpoint belongs to? By definition an unknown URL does not belong to any blueprint, so it cannot select a blueprint-specific error handler to use and will only invoke an app-wide error handler.
Thank you, now I do remember when you discussed that in the book.
Why doesn't
page_not_found
use@api_blueprint.app_errorhandler(404)
instead of@main.app_errorhandler(404)
?