diff --git a/src/main.py b/src/main.py index cba520c..acc9615 100644 --- a/src/main.py +++ b/src/main.py @@ -4,8 +4,9 @@ import logfire from fastapi import FastAPI, HTTPException, Request -from fastapi.responses import HTMLResponse, PlainTextResponse +from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse from fastapi.staticfiles import StaticFiles +from starlette.exceptions import HTTPException as StarletteHTTPException from src.settings import settings from src.templates_conf import templates @@ -29,6 +30,27 @@ def read_root(request: Request): return templates.TemplateResponse(request=request, name='index.html') +@app.exception_handler(StarletteHTTPException) +def custom_http_exception_handler( + request: Request, exc: StarletteHTTPException +): + if exc.status_code == HTTPStatus.NOT_FOUND: + if request.url.path.startswith('/api'): + return JSONResponse( + status_code=HTTPStatus.NOT_FOUND, + content={'detail': 'Not Found'}, + ) + + return templates.TemplateResponse( + request=request, + name='404.html', + context={'path': request.url.path}, + status_code=404, + ) + + raise exc + + @app.get('/api/list', response_class=PlainTextResponse) def list_templates(): """ diff --git a/src/templates/404.html b/src/templates/404.html new file mode 100644 index 0000000..d88c434 --- /dev/null +++ b/src/templates/404.html @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + 404 | Do Not Commit by Artefatto + + + + + + + +
+

Artefatto

+ +
+ +
+
+

404
Not Found

+

The page {{ path }} does not exist.

+

Go back home

+
+
+ + + + \ No newline at end of file