django-rest-framework
exception handler
build with
funtools.singledispatch
.
To use drf-exception-dispatcher
simply install it with your package manager,
e.g. to with pip
:
pip install drf-exception-dispatcher
Then simply use exception_dispatcher.handlers.exception_handler
(
or your own exception handler built on exception_dispatcher
) in Django's
settings REST_FRAMEWORK
section:
REST_FRAMEWORK = {
# ...
'EXCEPTION_HANDLER': 'exception_dispatcher.handlers.exception_handler',
# ...
}
Following settings are present to make default exception_dispatcher
handler
configurable:
EXCEPTION_DISPATCHER_SET_ROLLBACK
(defaults toTrue
) - indicate ifset_rollback
should be called before returning response from exception handlerEXCEPTION_DISPATCHER_API_EXCEPTION_PARSER
(defaults toexception_dispatcher.parsers.parse_rest_framework_api_exception'
) - import path to callable that is used to translate occurredexception
to response data
To add new handlers to exception_dispatchers
simply use dispatcher's
register()
method, e.g. to add handler of SuspiciousOperation
exceptions:
from exception_dispatcher.dispatchers import exception_dispatcher
from exception_dispatcher.types import ContextType
from rest_framework.response import Response
@exception_dispatcher.register
def handler_suspicious_operation(
exception: SuspiciousOperation,
context: ContextType,
) -> Response | None:
"""Handle Django's `SuspiciousOperation` exceptions."""
# custom ``exception` handler logic goes here
return None