2023-02-18 21:17:16 +04:00
|
|
|
"""Custom error pages for FastAPI app"""
|
|
|
|
|
|
|
|
from pathlib import Path
|
2023-02-22 21:40:21 +04:00
|
|
|
from typing import List
|
2023-02-18 21:17:16 +04:00
|
|
|
|
|
|
|
from fastapi import Request, Response
|
|
|
|
from fastapi import HTTPException
|
|
|
|
|
2023-02-20 12:41:29 +04:00
|
|
|
from . import Paths
|
2023-02-19 16:27:55 +04:00
|
|
|
from .. import respond
|
|
|
|
from .. import common
|
2023-02-18 21:17:16 +04:00
|
|
|
|
|
|
|
# Add other HTTP error codes
|
2023-02-22 21:40:21 +04:00
|
|
|
codes: List[int] = [404, 500]
|
2023-02-18 21:17:16 +04:00
|
|
|
|
|
|
|
|
2023-02-20 12:41:29 +04:00
|
|
|
class ErrorsPaths(Paths):
|
2023-02-18 21:17:16 +04:00
|
|
|
"""Sets up custom error pages,
|
|
|
|
inherited from paths.Paths"""
|
|
|
|
|
|
|
|
def add_paths(self) -> None:
|
|
|
|
|
2023-02-27 19:05:04 +04:00
|
|
|
# For each HTTP code specified above
|
2023-02-18 21:17:16 +04:00
|
|
|
for code in codes:
|
|
|
|
self.add_handler(code)
|
2023-02-27 19:05:57 +04:00
|
|
|
|
2023-02-18 21:17:16 +04:00
|
|
|
def add_handler(self, code: int) -> None:
|
|
|
|
"""Adds an error handler to FastAPI app.
|
|
|
|
Only for internal use!
|
|
|
|
|
|
|
|
Args:
|
|
|
|
code (int): HTTP error code
|
|
|
|
"""
|
|
|
|
|
2023-02-27 19:05:04 +04:00
|
|
|
# Jinja template file name
|
|
|
|
# e.g. 404.html for 404 code
|
2023-02-19 16:19:18 +04:00
|
|
|
file = Path(common.templates_dir) / f'{code}.html'
|
2023-02-18 21:17:16 +04:00
|
|
|
|
2023-02-27 19:05:04 +04:00
|
|
|
# Exit from the function
|
|
|
|
# if the template does not exist
|
2023-02-18 21:17:16 +04:00
|
|
|
if not file.exists():
|
|
|
|
return
|
|
|
|
|
|
|
|
@self.app.exception_handler(code)
|
|
|
|
async def handler(req: Request, exc: HTTPException) -> Response:
|
|
|
|
|
2023-02-27 19:05:04 +04:00
|
|
|
# Respond with the template
|
2023-02-18 21:17:16 +04:00
|
|
|
return respond.with_tmpl(
|
|
|
|
f'{code}.html',
|
|
|
|
code=code,
|
|
|
|
request=req,
|
|
|
|
exc=exc,
|
|
|
|
)
|