Exception handlers
The library provides a shared DRF exception handler that converts errors into
the DSO-compliant application/problem+json format.
Projects can register custom exception handlers using the exception handler registry.
- vng_api_common.exception_handling.exception_handler(exc: Exception, context: dict[str, object]) Response | None
Transform 4xx and 5xx errors into DSO-compliant Problem JSON shape.
This exception handler can be enabled by either using the
BASE_REST_FRAMEWORKsettings fromvng_api_common.apior by explicitly setting:REST_FRAMEWORK = { ... "EXCEPTION_HANDLER": "vng_api_common.exception_handling.exception_handler", ... }
Supports project-level custom exception handlers via the registry.
- vng_api_common.exception_handling.register_exception_handler(exc_type: Type[Exception], handler: Callable[[Exception, dict[str, object]], Response]) None
Register a custom exception handler.
Projects using
commonground-api-commonmay want to customize the error response for specific domain exceptions without duplicating the fullexception_handler()implementation.This function allows registering a handler for a specific exception type.
The handler:
receives the raised exception and the DRF exception context
must return a DRF
Response
Example
from rest_framework import status from rest_framework.response import Response from rest_framework.exceptions import ErrorDetail from vng_api_common.exception_handling import register_exception_handler class ZaakLockedError(Exception): status_code = 409 default_detail = "Zaak is locked" default_code = "zaak_locked" def zaak_locked_handler(exc, context): exc.detail = ErrorDetail( "Zaak is locked and cannot be updated", code="zaak_locked", ) return Response( {"detail": exc.detail}, status=status.HTTP_409_CONFLICT, ) register_exception_handler(ZaakLockedError, zaak_locked_handler)
Notes
Handlers are matched using
isinstanceso subclasses are supported.Responses are still finalized into the DSO-compliant problem format.