Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Response Handling #36

Open
hiruthikj opened this issue Oct 9, 2023 · 1 comment
Open

Response Handling #36

hiruthikj opened this issue Oct 9, 2023 · 1 comment

Comments

@hiruthikj
Copy link

I am planning to use Response Structure like this (https://google.github.io/styleguide/jsoncstyleguide.xml?showone=error#error)

{
  "error": {
    "code": 404,
    "message": "File Not Found",
    "errors": [{
      "domain": "Calendar",
      "reason": "ResourceNotFoundException",
      "message": "File Not Found
    }]
  }
}

Can anyone suggest the best way to handle this?
I handled it for RequestValidationException of Pydantic, but for other Exceptions, I am not sure how to handle it.

For RequestValidationException

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    error_response = {
        "error": {
            "code": status.HTTP_422_UNPROCESSABLE_ENTITY,
            "message": "Request Validation Failed",
            "errors": exc.errors(),
        }
    }
    return JSONResponse(
        content=jsonable_encoder(error_response),
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
    )
@hiruthikj
Copy link
Author

I have tried this

@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: RequestValidationError):
    error_response = {
        "error": {
            "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
            "message": "Internal Server Error",
            "errors": exc.errors(),
        }
    }
    return JSONResponse(
        content=jsonable_encoder(error_response),
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
    )

This doesn't seem to work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant