tmpl-fastapi/app/paths/errors.py
2023-02-27 19:05:04 +04:00

53 lines
1.3 KiB
Python

"""Custom error pages for FastAPI app"""
from pathlib import Path
from typing import List
from fastapi import Request, Response
from fastapi import HTTPException
from . import Paths
from .. import respond
from .. import common
# Add other HTTP error codes
codes: List[int] = [404, 500]
class ErrorsPaths(Paths):
"""Sets up custom error pages,
inherited from paths.Paths"""
def add_paths(self) -> None:
# For each HTTP code specified above
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
"""
# Jinja template file name
# e.g. 404.html for 404 code
file = Path(common.templates_dir) / f'{code}.html'
# Exit from the function
# if the template does not exist
if not file.exists():
return
@self.app.exception_handler(code)
async def handler(req: Request, exc: HTTPException) -> Response:
# Respond with the template
return respond.with_tmpl(
f'{code}.html',
code=code,
request=req,
exc=exc,
)