thermobased / flask-webapp

0 stars 0 forks source link

Handle UNIQUE constraint failed error correctly #1

Closed gnull closed 8 months ago

gnull commented 9 months ago

If you try to create the same user twice, the app throws this error:

[2023-12-13 19:25:47,419] ERROR in app: Exception on /register [POST]
Traceback (most recent call last):
  File "/home/io/andrei/flask-webapp/.venv/lib/python3.11/site-packages/flask/app.py", line 1455, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/io/andrei/flask-webapp/.venv/lib/python3.11/site-packages/flask/app.py", line 869, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/io/andrei/flask-webapp/.venv/lib/python3.11/site-packages/flask/app.py", line 867, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/io/andrei/flask-webapp/.venv/lib/python3.11/site-packages/flask/app.py", line 852, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/io/andrei/flask-webapp/main.py", line 22, in register
    cur.execute("INSERT INTO items(login, password) VALUES(?, ?)", (u, p))
sqlite3.IntegrityError: UNIQUE constraint failed: items.login

It happens because our table has a constraint saying that usernames must be unique (the login TEXT unique part):

https://github.com/thermobased/flask-webapp/blob/5ac124c49d5c7c7ab466f4d83daa24ba7dd3d06a/create.sql#L1

And when our Python code tries to execute an INSERT statement that would violate this constraint, Sqlite refuses to apply it and throws an error. We should handle this error proprtly, and instead of crashing the app we should catch it and report to the user something like "error: given user already exists".

Ivan