r/FastAPI • u/Krypton_Rimsdim • Sep 18 '21
Question [HELP] FastAPI Error Handling : Need to handle Primary Key and Unique Key Violations but the Code never runs the Exception Handling part
https://stackoverflow.com/questions/69230244/fastapi-error-handling-need-to-handle-primary-key-and-unique-key-violations-bu
3
Upvotes
1
u/ResponseSpecial Sep 18 '21
There are a few things here
Your 'query' holds the string you assign it to, so it'll never be None.
If the execution of the query violates database restrictions, it will most definetely throw an ecxeption. I am guessing this is what currently happens. You can probably check out what exactly is thrown in the running log.
When you found out which exception is thrown by the execution, you can catch it using try...except.
For environment variables, try using a file which contains them and which is excluded from git. Check out the 'dotenv' package.
Usually you'd like to have some kind of abstraction in your application. Meaning that the function which is accessible through the api for the user does not also do the database query but calls another module to do it.