Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Unable to catch Exception via exception_handlers since FastAPI 0.70.0 #4025

@manlix

Description

@manlix

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

################################################
#
# Pay attention: below is Python 3.10 syntax
#
################################################

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import ValidationError

async def internal_server_error(request: Request, exc: Exception | ValidationError) -> "JSONResponse":
    return JSONResponse(content={"detail": "Internal Server Error"}, status_code=500)

app = FastAPI(
    exception_handlers={
        Exception: internal_server_error,
        ValidationError: internal_server_error,
    },
)

@app.get("/call_me")
async def raise_exception() -> None:
    raise Exception("I am exception.")

Description

  • Open the browser and call the endpoint: /call_me
  • It returns plain text: Internal Server Error
  • But I excepted it return JSON: {"detail": "Internal Server Error"}

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.70.0

Python Version

Python 3.10.0

Additional Context

It works fine on FastAPI 0.68.2.
Issue is also affected 0.69.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions