aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--fatcat_scholar/templates/error.html31
-rw-r--r--fatcat_scholar/web.py31
2 files changed, 61 insertions, 1 deletions
diff --git a/fatcat_scholar/templates/error.html b/fatcat_scholar/templates/error.html
new file mode 100644
index 0000000..2eafa8d
--- /dev/null
+++ b/fatcat_scholar/templates/error.html
@@ -0,0 +1,31 @@
+{% extends "base.html" %}
+
+{% block title %}
+{{ error.status_code }} - {{ super() }}
+{% endblock %}
+
+{% block main %}
+<center>
+ <div style="font-size: 8em;">{{ error.status_code }}</div>
+ <div style="font-size: 3em;">
+ {% if error.status_code == 404 %}
+ {% trans %}Not Found{% endtrans %}
+ {% elif error.status_code == 403 %}
+ {% trans %}Access Forbidden{% endtrans %}
+ {% elif error.status_code == 400 %}
+ {% trans %}Request Error{% endtrans %}
+ {% elif error.status_code > 500 and error.status_code < 600 %}
+ {% trans %}Internal Error{% endtrans %}
+ {% endif %}
+ </div>
+</center>
+{% if error.detail and error.detail not in ["Not Found", "Server Error", "Bad Request"] %}
+ <div class="ui icon error message">
+ <i class="ban icon"></i>
+ <div class="content">
+ <div class="header"></div>
+ <p>{{ error.detail }}
+ </div>
+ </div>
+{% endif %}
+{% endblock %}
diff --git a/fatcat_scholar/web.py b/fatcat_scholar/web.py
index 6e3524d..05bced1 100644
--- a/fatcat_scholar/web.py
+++ b/fatcat_scholar/web.py
@@ -10,10 +10,11 @@ from typing import Optional, Any
import babel.support
from fastapi import FastAPI, APIRouter, Request, Depends, Response
from fastapi.staticfiles import StaticFiles
-from fastapi.responses import PlainTextResponse
+from fastapi.responses import PlainTextResponse, JSONResponse
import sentry_sdk
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
from starlette_prometheus import metrics, PrometheusMiddleware
+from starlette.exceptions import HTTPException as StarletteHTTPException
from fatcat_scholar.config import settings, GIT_REVISION
from fatcat_scholar.hacks import Jinja2Templates, parse_accept_lang
@@ -252,6 +253,34 @@ async def robots_txt(response_class: Any = PlainTextResponse) -> Any:
else:
return PlainTextResponse(ROBOTS_DISALLOW)
+@app.exception_handler(StarletteHTTPException)
+async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> Any:
+ """
+ This is the generic handler for things like 404 errors.
+ """
+ # TODO: what if there is an error in any of the detection code?
+ content = ContentNegotiation(request)
+
+ if content.mimetype == "text/html":
+ lang = LangPrefix(request)
+ return i18n_templates[lang.code].TemplateResponse(
+ "error.html",
+ {
+ "request": request,
+ "locale": lang.code,
+ "lang_prefix": lang.prefix,
+ "error": exc,
+ },
+ status_code=exc.status_code,
+ )
+ else:
+ resp = {'status_code': exc.status_code}
+ if exc.detail:
+ resp['detail'] = exc.detail
+ return JSONResponse(
+ status_code=exc.status_code,
+ content=resp,
+ )
# configure middleware