diff options
author | 2022-02-21 23:12:22 +0100 | |
---|---|---|
committer | 2022-02-21 23:24:23 +0100 | |
commit | c7f4d04acbdf4ac25eaa12009ce54fdd7e23591c (patch) | |
tree | 5026ef3788e33305fa995ea806d09ae0a57ea129 /pydis_site/apps/api | |
parent | Merge pull request #666 from python-discord/integrityerror-duplicate-infracti... (diff) |
Assert we're dealing with the unique constraint
Diffstat (limited to 'pydis_site/apps/api')
-rw-r--r-- | pydis_site/apps/api/viewsets/bot/infraction.py | 24 |
1 files changed, 16 insertions, 8 deletions
diff --git a/pydis_site/apps/api/viewsets/bot/infraction.py b/pydis_site/apps/api/viewsets/bot/infraction.py index 31e8ba40..7e7adbca 100644 --- a/pydis_site/apps/api/viewsets/bot/infraction.py +++ b/pydis_site/apps/api/viewsets/bot/infraction.py @@ -281,11 +281,19 @@ class InfractionViewSet( """ try: return super().create(request, *args, **kwargs) - except IntegrityError: - raise ValidationError( - { - 'non_field_errors': [ - 'This user already has an active infraction of this type.', - ] - } - ) + except IntegrityError as err: + # We need to use `__cause__` here, as Django reraises the internal + # UniqueViolation emitted by psycopg2 (which contains the attribute + # that we actually need) + # + # _meta is documented and mainly named that way to prevent + # name clashes: https://docs.djangoproject.com/en/dev/ref/models/meta/ + if err.__cause__.diag.constraint_name == Infraction._meta.constraints[0].name: + raise ValidationError( + { + 'non_field_errors': [ + 'This user already has an active infraction of this type.', + ] + } + ) + raise # pragma: no cover - no other constraint to test with |