I'm writing an application using django framework and was thinking about writing something like a rest controller, cos keeping the exception handling logic in one place seems like a good idea. I don't know what would be the right way to do this, but I came up with writing a decorator that comprises a bunch of exceptions that may well be thrown by various methods and thus, that decorator is used on each of them.
def exception_handler(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except Error1 as error:
return Response(
{"Error": str(error)},
status=status.HTTP_400_BAD_REQUEST
)
except Error2 as error:
return Response(
{"Error": str(error)},
status=status.HTTP_404_NOT_FOUND
)
except Error3 as error:
return Response(
{"Error": str(error)},
status=status.HTTP_503_SERVICE_UNAVAILABLE
)
return wrapper
Where Error1, Error2 and Error3 are just some abstract errors. In my applications there's more of them indeed.
Simple controller (aka django view) may look something like this:
class DeviceView(viewsets.ModelViewSet):
lookup_field = 'id'
serializer_class = DeviceSerializer
@exception_handler
def create(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(data=request.data)
return Response(status=status.HTTP_200_OK)
So basically if any of the exceptions is thrown it will be handled in the appropriate way. One of the problems that I see here is that if it's not me who raises an exception with a desired message:
if some_condition:
raise SomeException("Something happened")
it will be a default one and oftentimes I would prefer to alter it. So I start feeling somewhat uncomfortable about controlling what message should be shown to the client. The best that I could come up with right now is this:
try:
this_function_throws_someexception(args)
except SomeException:
raise SomeException("Here is the message I want to show to the client")
Which means I have to re-raise the exception thrown with the message I'd want it to be raised. My first question is "Is this the best way to deal with it?". And the second question is : "Is the whole approach to exception handling good?"