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.

[QUESTION] Handling Exception Response format

See original GitHub issue

Hello. I want to change the validation error response and make it inside app object.

I’ve found this example:

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
    )

But can’t understand how to add this function to app object without decorator:

app = FastAPI(
    title='Bla API',
    description='Bla description',
    APIRoute('/api', api.toggle, methods=['POST'],
             description='Switch interface state',
             response_description='Interface successfully switched',
             response_class=JSONResponse,
             response_model=api.Success,
             responses={**api.post_responses},
             ),
...

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:20 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
horseintheskycommented, Jul 16, 2020

@MacMacky Ok. Thanks again for your help.

1reaction
davemaharshi7commented, Jul 12, 2020

may be you can try this:

"""For managing validation error for complete application."""
from typing import Union
from fastapi.exceptions import RequestValidationError
from fastapi.openapi.constants import REF_PREFIX
from fastapi.openapi.utils import validation_error_response_definition
from pydantic import ValidationError
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY


async def http422_error_handler(
    _: Request, exc: Union[RequestValidationError, ValidationError],
) -> JSONResponse:
    """To handle unprocessable request(HTTP_422) and log accordingly to file.

    Args:
        _ (Request): Request object containing metadata about Request
        exc (Union[RequestValidationError, ValidationError]): to handle RequestValidationError,
            ValidationError

    Returns:
        JSONResponse: JSON response with required status code.
    """
    return JSONResponse(
        {"error": exc.errors()}, status_code=HTTP_422_UNPROCESSABLE_ENTITY,
    )


validation_error_response_definition["properties"] = {
    "errors": {
        "title": "Errors",
        "type": "array",
        "items": {"$ref": "{0}ValidationError".format(REF_PREFIX)},
    },
}

And in main.py

app.add_exception_handler(RequestValidationError, http422_error_handler)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Best Practices for REST API Error Handling - Baeldung
3.1.​​ The simplest way we handle errors is to respond with an appropriate status code. Here are some common response codes: 400 Bad...
Read more >
Guide to Spring Boot REST API Error Handling - Toptal
Let's learn how to handle exceptions in Spring Boot properly and wrap them into a better JSON representation to make life easier for...
Read more >
Handling Exceptions Returned from the Web API
You'll learn to how to return 500, 404, and 400 exceptions and how to handle them on your Web page. Basic Exception Handling...
Read more >
Servlet Exception and Error Handling Example Tutorial
The problem with this response is that it's of no value to user. Also it's showing our application classes and server details to...
Read more >
Complete Guide to Exception Handling in Spring Boot
Spring provides a very elegant solution to this problem in form of “controller advice”. Let's study them. @ControllerAdvice. Why is it called " ......
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