Skip to content

Commit

Permalink
Use nested transaction to handle integrity error
Browse files Browse the repository at this point in the history
The notes in the "avoid catching exceptions" callout here
(https://docs.djangoproject.com/en/5.0/topics/db/transactions/#controlling-transactions-explicitly)
say to do something like this to isolate error handling without stepping
on the operation of the transactions themselves.
  • Loading branch information
waxlamp committed Aug 8, 2024
1 parent b5ad8b2 commit 7e04c83
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions dandiapi/zarr/views/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,14 @@ def create(self, request):
if dandiset.embargo_status != Dandiset.EmbargoStatus.OPEN:
raise ValidationError('Cannot add zarr to embargoed dandiset')
zarr_archive: ZarrArchive = ZarrArchive(name=name, dandiset=dandiset)
try:
with transaction.atomic():
zarr_archive.save()
with transaction.atomic():
try:
with transaction.atomic():
zarr_archive.save()
except IntegrityError as e:
raise ValidationError('Zarr already exists') from e

audit.create_zarr(dandiset=dandiset, user=request.user, zarr_archive=zarr_archive)
except IntegrityError as e:
raise ValidationError('Zarr already exists') from e
audit.create_zarr(dandiset=dandiset, user=request.user, zarr_archive=zarr_archive)

serializer = ZarrSerializer(instance=zarr_archive)
return Response(serializer.data, status=status.HTTP_200_OK)
Expand Down

0 comments on commit 7e04c83

Please sign in to comment.