Browse Source

Start wrapping errors in our own

Getty Ritter 4 years ago
parent
commit
4635695a44
4 changed files with 20 additions and 5 deletions
  1. 8 0
      lc/error.py
  2. 8 4
      lc/model.py
  3. 2 0
      stubs/peewee.py
  4. 2 1
      tests/model.py

+ 8 - 0
lc/error.py

@@ -0,0 +1,8 @@
+from dataclasses import dataclass
+
+@dataclass
+class UserExists(Exception):
+    name: str
+
+    def __str__(self):
+        return f"A user named {self.name} already exists."

+ 8 - 4
lc/model.py

@@ -4,6 +4,7 @@ import peewee
 import typing
 
 import lc.config as c
+import lc.error as e
 import lc.request as r
 
 
@@ -24,10 +25,13 @@ class User(Model):
     @staticmethod
     def from_request(user: r.User) -> "User":
         passhash = pwd.hash(user.password)
-        return User.create(
-            name=user.name,
-            passhash=passhash,
-        )
+        try:
+            return User.create(
+                name=user.name,
+                passhash=passhash,
+            )
+        except peewee.IntegrityError:
+            raise e.UserExists(name=user.name)
 
     def authenticate(self, password: str) -> bool:
         return pwd.verify(password, self.passhash)

+ 2 - 0
stubs/peewee.py

@@ -44,3 +44,5 @@ def BooleanField(unique: bool = False) -> Any:
 
 def ForeignKeyField(key: object, null: bool = None, backref: str = "") -> Any:
     pass
+
+class IntegrityError(Exception): pass

+ 2 - 1
tests/model.py

@@ -2,6 +2,7 @@ import peewee
 import pytest
 
 import lc.config as c
+import lc.error as e
 import lc.request as r
 import lc.model as m
 
@@ -48,7 +49,7 @@ class TestDB:
     def test_no_duplicate_users(self):
         name = "gdritter"
         u1 = self.mk_user(name=name)
-        with pytest.raises(peewee.IntegrityError):
+        with pytest.raises(e.UserExists):
             u2 = self.mk_user(name=name)
 
     def test_get_or_create_tag(self):