I am trying to implement Exception Handling in FastAPI.
I have Try along with Exception block in which I am trying to implement Generic Exception if any other exception occurs than HTTPExceptions mentioned in Try Block. In generic exception, I would like to print details of actual exception in format { "details": "Actual Exception Details" } However, in below implementation, even though any exception in Try is raised it goes to Except block and prints that exception.
I Try block specific exceptions, I am trying to have a CustomException class that can print the details of custom exception provded name of exception.
@app.get("/school/studentclass")
async def get_student_class(id: int, stream: str, rank: int = 1):
try:
student = Student(id=id,stream=stream,rank=1)
if (student.id != 0):
if (student.stream is not None or student.stream != ''):
if(student.rank!= 0):
// Student Class is used to represent API Output : Student_Class_Name and Student_Class_Room and Student_Class_Teacher
studentClass = StudentClass()
// Processing Logic to get Student Class
return JSONResponse(content=studentClass)
else:
raise HTTPException(status_code = 422, detail = "Student Rank is not right", headers={"X-Error": "Student Rank is not right"})
else:
raise HTTPException(status_code = 422, detail="Student Stream is not right", headers={"X-Error": "Student Stream is not right"})
else:
raise HTTPException(status_code = 422, detail="Student Id is not right", headers={"X-Error": "Student Id is not right"})
except Exception as e:
raise HTTPException(status_code = 418, detail=str(e))
Custom Exception Class
class CustomException(Exception):
def __init__(self, name: str):
self.name = name
For the second question, I tried to implement as below but it isn't working this way
else:
raise HTTPException(status_code = 422, detail = CustomException(name = "Invalid Student Rank"), headers={"Error": "Invalid Student Rank"})
The Error Handling is done as follows:
@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
print(f"HTTP Error: {repr(exc)}")
return await http_exception_handler(request, exc)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
print(f"Invalid Data: {exc}")
return await request_validation_exception_handler(request, exc)