HTTP Response – Technical Reasons Not to Use Custom Response Code Text

http-response

Over the years, I have seen quite a few questions on this site along the lines of "can I invent my own HTTP response codes"? Generally asked by those who are developing both the server and client. The responses tend to go towards sticking with standard codes.

If I stick with standard HTTP status code numbers, is there any technical reason not to use custom text in order to differentiate between, let's say, multiple 501 responses?

To reiterate, no client except mine will ever see these values, which are returned by AJAX in repose to authenticated requests.

Best Answer

An alternative approach would be to include a response body containing the detailed failure reason, for example in a JSON object. This would be comparable to the customized 404 pages which are often delivered to browsers when a non-existent web page is opened.

For example, if your backend is written in Python using Django, you could implement a middleware function (see https://docs.djangoproject.com/en/3.0/topics/http/middleware/) to catch exceptions and return a 500 error with some error JSON object (note this is completely untested, just use it to get an idea how it could be done):

import sys, traceback
from django.http import JsonResponse

def exception_handling_middleware(get_response):

    def middleware(request):

        try:
            # call inner handler
            return get_response(request)
        except BaseException:
            # if any exception happens, return an error response
            # with a 500 status code
            return JsonResponse(
              {
                "error": str(sys.exc_info()[1]),
                "traceback": traceback.format_exc()
              },
              status=500)