1

I simply want to surface an Exception message as a bad response in DRF.

The Exception can come from anywhere in the request. So for example, some nested function can have:

raise Exception('Something went wrong at this particular point')

And then in my view handler, i'd simply catch the Exception and raise it:

    except Exception as e:
        raise e

This raises an Exception in my application, but there is no way to parse the response to get my custom message.

I can try this:

return Response(e, status=status.HTTP_400_BAD_REQUEST)

But that returns an Exception itself:

Object of type Exception is not JSON serializable

So how can I simply return my Exception message as a 400?

1 Answer 1

1

You'll likely need to cast e to a string first: try:

return Response(str(e), status=status.HTTP_400_BAD_REQUEST)

The underlying Response function is trying to serialize it, and the Exception class can't be converted to JSON. You might want to return a more complete json structure too:

return Response({'error_message': str(e)}, status=status.HTTP_400_BAD_REQUEST)
Sign up to request clarification or add additional context in comments.

1 Comment

Genius. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.