Search code examples
fastapipostman-testcase

Customise Status codes in place of 500: Internal Server Error in FastAPI using Postman


I'm very new in using FastAPI and postman. When I am sending a POST request with a body (input data), I'm getting Success code 200 and also intended Response.

Now, I want to tweak my input data to make my code fail intentionally. This is also happening. But the status code is coming to be 500 and Internal Server Error is being displayed in response.

I want to manually give a status code in each case of failure and also some related output in Response. How to achieve this goal?


Solution

  • Detailed Solution can be found out on https://fastapi.tiangolo.com/tutorial/handling-errors/.

    A quick solution is to just add following line in the function where you are returning output using try and except statements:

    try:
        output
    except Exception:
        raise HTTPException(status_code=406, detail="New Error Found")