Home > Blockchain >  Django - Returning full exception trace to front-end on a 400
Django - Returning full exception trace to front-end on a 400

Time:12-20

So just for closed beta and internal testing purposes I'm trying to return the exception with the 400 error in my Django server. Here is an example below of how I am doing this in Django code. I have a partner working on the front-end and they said they can't get the error out of the 400 response. I assumed it'd be in like response.body['error']. How can I send back a 400 with the full error trace in a way that can be pulled out by the front-end?

except Exception as e:
    return Response(dict(error=str(e),
                         user_message=error_message_generic),
                    status=status.HTTP_400_BAD_REQUEST)

CodePudding user response:

The most common approach is this:

from django.http import JsonResponse, HttpResponseBadRequest

return HttpResponseBadRequest(JsonResponse({
    "error": "Malformed request",
    # Any other fields you'd want
}))

See more at official docs.

If you are interested on returning specifically a traceback of your back-end exception, you can go this way:


from django.http import JsonResponse, HttpResponseBadRequest
import traceback

...
except Exception as e:
    return HttpResponseBadRequest(JsonResponse({
        "error": "Malformed request",
        "traceback": traceback.format_exc()
    }))

traceback.format_exc()

But it's not the best way to do it in all cases. If you are sure, that exception is related to user's input, then traceback wouldn't be so helpful for user. You should better use Serializer, whose validation would be much better. If you're just delivering information about unknown error I'd advise to use HttpResponseServerError and log your exceptions anywhere, to sentry, for example.

  • Related