zhanymkanov/fastapi-best-practices

Response Handling

Opened this issue · 1 comments

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,
    )

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