Skip to content

How to setup different exception_handler's for different routes or http_handlers? #5519

@oObelix

Description

@oObelix

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

from fastapi import FastAPI

app = FastAPI()


@app.exception_handler(RequestValidationError)
async def validation_exception(request, exc):
    return Response(
        content='Incorrect symbol',
        media_type="text/html",
        status_code=404
    )


@app.get('/')
def foo(q: str = Query(regex='^[0-9]+$')):
   pass

@app.post('/')
def bar(q: str = Query(regex='^[0-9]+$')):
    pass

Description

I can add @app.exception_handler(RequestValidationError) for all Validation Errors like in code above. How to add different exception_handler's to get (foo()) and post (bar()) handlers with same regex validation?

from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def foo(q: str = Query(regex='^[0-9]+$')):
   pass

@app.post('/')
def bar(q: str = Query(regex='^[0-9]+$')):
    pass

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.85.1

Python Version

3.10

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions