51 lines
1.1 KiB
Python
51 lines
1.1 KiB
Python
|
"""Custom error pages for FastAPI app"""
|
||
|
|
||
|
from pathlib import Path
|
||
|
|
||
|
from fastapi import Request, Response
|
||
|
from fastapi import HTTPException
|
||
|
|
||
|
from . import paths
|
||
|
from . import respond
|
||
|
from .common import settings
|
||
|
|
||
|
# Add other HTTP error codes
|
||
|
codes = [404, 500]
|
||
|
|
||
|
|
||
|
class ErrorsPaths(paths.Paths):
|
||
|
"""Sets up custom error pages,
|
||
|
inherited from paths.Paths"""
|
||
|
|
||
|
def add_paths(self) -> None:
|
||
|
|
||
|
for code in codes:
|
||
|
self.add_handler(code)
|
||
|
|
||
|
def add_handler(self, code: int) -> None:
|
||
|
"""Adds an error handler to FastAPI app.
|
||
|
Only for internal use!
|
||
|
|
||
|
Args:
|
||
|
code (int): HTTP error code
|
||
|
"""
|
||
|
|
||
|
tmpl_dir = (
|
||
|
Path(__file__).parent /
|
||
|
settings.templates_dir
|
||
|
)
|
||
|
file = tmpl_dir / f'{code}.html'
|
||
|
|
||
|
if not file.exists():
|
||
|
return
|
||
|
|
||
|
@self.app.exception_handler(code)
|
||
|
async def handler(req: Request, exc: HTTPException) -> Response:
|
||
|
|
||
|
return respond.with_tmpl(
|
||
|
f'{code}.html',
|
||
|
code=code,
|
||
|
request=req,
|
||
|
exc=exc,
|
||
|
)
|