question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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

See original GitHub issue

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

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
yinziyan1206commented, Oct 19, 2022

use different app, and mount it on main app. Its a basic usage in starlette

1reaction
JarroVGITcommented, Oct 18, 2022

Well, out of the box you can’t have different exception handlers for the same Exception subtype. That is because the exception handlers are registered at the upmost app level.

One way of dealing with your requirement is to create a dependency function that takes the parameter as its parameter, but without the regex. This logic would then be moved to the function itself, and based on the request method you could raise a specific Exception. But that becomes unwieldy if your real-life code is a bit more complex than the example you gave (which I assume it is).

On the other hand (and this is not helping you at all, I realise) you could argue that an error response from an API framework in the form of html is… sketchy and should be JSON in the first place?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Handling Exceptions in Undertow with Composition
Just create an ExceptionHandler instance and add a HttpHandler for each Exception type you wish to handle. Make sure you main route is...
Read more >
How we can get different @ExceptionHandler ... - Stack Overflow
I have a single class with 2 different controllers. I want to write @ExceptionHandler specific to controller. For example, for controller 1, ...
Read more >
io.undertow.server.handlers.ExceptionHandler java code ...
Returns a handler that maps exceptions to additional handlers * @param next The next handler * @return The exception handler */ public static ......
Read more >
StubbornJava/ExceptionHandlingServer.java at master - GitHub
private static final HttpHandler ROUTES = new RoutingHandler() .get("/throwWebException", ExceptionHandlers::throwWebException).
Read more >
Handlers (Undertow 1.3.0.CR1 API)
Handler that appends the JVM route to the session cookie ... Unless you need to decode to something other than UTF-8 you should...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found