From 59219ebfd53fb56ceb5a8498f535fe75922f8458 Mon Sep 17 00:00:00 2001 From: Konrad Mohrfeldt <konrad.mohrfeldt@farbdev.org> Date: Mon, 21 Mar 2022 15:15:37 +0100 Subject: [PATCH] feat: API errors now come with an optional code This change allows clients to identify specific errors by an optional code provided as part of any APIException instances raised in our code. This code: ```py raise ValidationError( "Please provide a correct date and time", code="time-invalid", ) ``` now returns an error object via the API with a message and a code property making error processing on the client side easy for both humans and machines and looks like this: ```json { "message": "Please provide a correct date and time", "code": "time-invalid" } ``` --- steering/settings.py | 1 + steering/views.py | 8 ++++++++ 2 files changed, 9 insertions(+) create mode 100644 steering/views.py diff --git a/steering/settings.py b/steering/settings.py index 16eb0590..b36e961a 100644 --- a/steering/settings.py +++ b/steering/settings.py @@ -109,6 +109,7 @@ REST_FRAMEWORK = { "program.auth.OidcOauth2Auth", ], "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"], + "EXCEPTION_HANDLER": "steering.views.full_details_exception_handler", } INSTALLED_APPS = ( diff --git a/steering/views.py b/steering/views.py new file mode 100644 index 00000000..0eb278d5 --- /dev/null +++ b/steering/views.py @@ -0,0 +1,8 @@ +from rest_framework.exceptions import APIException +from rest_framework.views import exception_handler + + +def full_details_exception_handler(exc, context): + if isinstance(exc, APIException): + exc.detail = exc.get_full_details() + return exception_handler(exc, context) -- GitLab