python / intermediate
Snippet
Custom View Exception Handler Decorator for Database Errors
Python closure decorators wrap view functions to capture specific runtime exceptions like Django's `IntegrityError`. Using `functools.wraps` preserves view metadata while centralizing HTTP error response formatting.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from functools import wrapsfrom django.db import IntegrityErrorfrom django.http import JsonResponsedef handle_database_errors(view_func):@wraps(view_func)def wrapper(request, *args, **kwargs):try:return view_func(request, *args, **kwargs)except IntegrityError as err:return JsonResponse({"error": "Integrity constraint violation","details": str(err)}, status=400)return wrapper
django
Breakdown
1
def handle_database_errors(view_func):
Defines a higher-order decorator function taking a view function as argument.
2
@wraps(view_func)
Preserves the original view function's name, docstring, and signature.
3
try:
Executes the wrapped view function inside a guarded try block.
4
except IntegrityError as err:
Catches database integrity constraint violations (e.g., duplicate unique fields).
5
return JsonResponse({ ... }, status=400)
Returns a structured JSON error payload with HTTP 400 Bad Request status.