r/FastAPI • u/pk028382 • Jan 19 '21
Question How to override default 404 route not found
Sorry this is probably a very noob question.
So I google and only found very few issues on this. But none of them answers how to catch only route not found. Both of the following links are saying how to catch all errors, if I understand correctly.
https://fastapi.tiangolo.com/tutorial/handling-errors/
https://stackoverflow.com/questions/62986778/fastapi-handling-and-redirecting-404
The doc doesn't even document how to override the default error message {"detail":"Not Found"} . Am I missing something?
I can of course catch all errors then handle them individually but it seems over-complicating things and this is a weird approach to solve this common issue.
I am actually using fastapi to build a small traditional HTML website - none of my route returns JSON.
I know it's of a misuse of the framework but I thought since it supports Template and HTML response so I just give it a try. Or should I just switch back to Flask?
4
Jan 19 '21
When looking at the source for the FastAPI class you can see that it directly inherits from Starlette and accepts a parameter called "exception_handlers":
https://github.com/tiangolo/fastapi/blob/master/fastapi/applications.py
I have not tried this, but I guess you should be able to use code as described in the Starlette documentation to specify custom exception handlers:
1
u/Deadly_chef Jan 19 '21
There is a whole chapter in the tutorial on exception handling and overwriting the default handlers
1
2
u/[deleted] Jan 19 '21