|
| 1 | +""" |
| 2 | +Run this example: |
| 3 | +$ fastapi dev examples/override.py |
| 4 | +
|
| 5 | +To see a custom starlette 405 error response. |
| 6 | +$ curl http://localhost:8000/not-allowed |
| 7 | +
|
| 8 | +To see a custom starlette 404 error response. |
| 9 | +$ curl http://localhost:8000/not-found |
| 10 | +""" |
| 11 | + |
| 12 | +import logging |
| 13 | + |
| 14 | +import fastapi |
| 15 | +from starlette.exceptions import HTTPException |
| 16 | + |
| 17 | +from fastapi_problem.handler import ExceptionHandler, add_exception_handler |
| 18 | +from fastapi_problem.error import NotFoundProblem, Problem, ServerProblem, StatusProblem |
| 19 | + |
| 20 | +logging.getLogger("uvicorn.error").disabled = True |
| 21 | + |
| 22 | + |
| 23 | +class CustomNotFoundProblem(NotFoundProblem): |
| 24 | + type_ = "not-found" |
| 25 | + title = "Endpoint not available." |
| 26 | + |
| 27 | + |
| 28 | +class CustomNotAllowedProblem(StatusProblem): |
| 29 | + status = 405 |
| 30 | + type_ = "method-not-allowed" |
| 31 | + title = "Method not allowed." |
| 32 | + |
| 33 | + |
| 34 | +status_mapping = { |
| 35 | + "404": (CustomNotFoundProblem, "The requested endpoint does not exist."), |
| 36 | + "405": (CustomNotAllowedProblem, "This method is not allowed."), |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +def http_exception_handler( |
| 41 | + _eh: ExceptionHandler, |
| 42 | + _request: fastapi.Request, |
| 43 | + exc: HTTPException, |
| 44 | +) -> Problem: |
| 45 | + exc, detail = status_mapping.get(str(exc.status_code)) |
| 46 | + return exc(detail) |
| 47 | + |
| 48 | + |
| 49 | +app = fastapi.FastAPI() |
| 50 | + |
| 51 | +add_exception_handler( |
| 52 | + app, |
| 53 | + handlers={HTTPException: http_exception_handler}, |
| 54 | +) |
| 55 | + |
| 56 | + |
| 57 | +@app.post("/not-allowed") |
| 58 | +async def method_not_allowed() -> dict: |
| 59 | + return {} |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + app.run() |
0 commit comments