'Fastapi async sql unique constraint throws Internal Server Error. Instead of returning a error message

I am using FastAPI and Async SQl. I have defined the schema with email unique. But when I pass the same email to the FastAPI route. It throws error on development server sqlite3.IntegrityError: UNIQUE constraint failed: users.email and returns a 500 Internal response via Postman. I want to show error as a message and not 500 error what should I do ?



Solution 1:[1]

what is happening is an Error that the client should NOT have access to,
there is a difference between validation errors that YOU define and between the ORM and database engine errors the library shows,
what you should do is check why are you sending a database query with an empty email! if you do so, the SQL engine will tell you that you can not put a NULL value there, which is something you did set.
there should be a validation before sending the query to the DB, in FastApi, such validation should be done with Pydantic models.
EDIT:
thanks to @Mecid X Recebli for his comment, I think the question has been changed and my answer is no longer valid. \

I answered as if you are sending an empty value of email to DB query, but your question says that you are sending a duplicate email, you should do email validation in the Pydantic schema, and that is by querying the DB for that email, if you have an account with the same email, raise a validation exception inside the validation method in the pydantic shema.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1