[2/3] HTML error pages for FastAPI

Message ID 20200728143327.GA564587@tsubame.mg0.fr
State New
Headers show
Series
  • [1/3] Update last login information on SSO login
Related show

Commit Message

Frédéric Mangano-Tarumi July 28, 2020, 2:33 p.m. UTC
---
 aurweb/asgi.py | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)

Patch

diff --git a/aurweb/asgi.py b/aurweb/asgi.py
index 60c7ade7..9293ed77 100644
--- a/aurweb/asgi.py
+++ b/aurweb/asgi.py
@@ -1,4 +1,7 @@ 
-from fastapi import FastAPI
+import http
+
+from fastapi import FastAPI, HTTPException
+from fastapi.responses import HTMLResponse
 from starlette.middleware.sessions import SessionMiddleware
 
 import aurweb.config
@@ -14,3 +17,14 @@  if not session_secret:
 app.add_middleware(SessionMiddleware, secret_key=session_secret)
 
 app.include_router(sso.router)
+
+
+@app.exception_handler(HTTPException)
+async def http_exception_handler(request, exc):
+    """
+    Dirty HTML error page to replace the default JSON error responses.
+    In the future this should use a proper Arch-themed HTML template.
+    """
+    phrase = http.HTTPStatus(exc.status_code).phrase
+    return HTMLResponse(f"<h1>{exc.status_code} {phrase}</h1><p>{exc.detail}</p>",
+                        status_code=exc.status_code)