python / intermediate
Snippet
Custom Exception Handler Mapping for Structured Error Responses
Creating custom exception classes inheriting from Python's Exception allows application views to raise domain-specific errors that can be trapped and formatted into unified JSON response structures.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
from django.http import JsonResponseclass DatabaseSyncError(Exception):def __init__(self, message, code=500):super().__init__(message)self.code = codedef handle_custom_exception(request, exc):if isinstance(exc, DatabaseSyncError):payload = {'error': str(exc), 'status_code': exc.code}return JsonResponse(payload, status=exc.code)return JsonResponse({'error': 'Unhandled internal server error'}, status=500)
django
Breakdown
1
class DatabaseSyncError(Exception):
Define a custom exception class extending base Python Exception to capture database sync failures.
2
def __init__(self, message, code=500):
Initialize custom error instance attributes such as descriptive error message and HTTP status code.
3
if isinstance(exc, DatabaseSyncError):
Check if the caught error matches the custom exception type before structuring the response payload.
4
return JsonResponse(payload, status=exc.code)
Return a structured JSON HTTP response using the exception's custom HTTP status code.