Error handling in Django REST framework - empty file returned instead of Error view
Question: I have a piece of code in a Django REST framework that looks like the
following. It works if the request arguments are valid, but if I specify a
non-valid search keyword, the browser returns an empty python file with length
of 0 bytes instead of an HTML error code. What am I doing wrong with respect
to error catching?

    
    
    from rest_framework.response import Response
    from rest_framework.views import APIView
    from rest_framework.renderers import JSONRenderer, StaticHTMLRenderer
    from rest_framework.exceptions import ParseError
    
    class GetDataseriesId(APIView):
        renderer_classes = (JSONRenderer, StaticHTMLRenderer)
    
        def get(self, request, format=None):
            # check format keyword and overrule default rendering format
            if 'format' in request.query_params:
                request.accepted_renderer.format = request.query_params['format']
            # build keyword arguments  (left out for clarity)
            search_dict = {'station_name':'Example'}
            # render query
            try:
                res = DataseriesIdSerializer(**search_dict)
            except Exception as e:
                raise ParseError("Malformed REST service request.\nDetail: %s", e)
            return Response(res.data)
    

The server error log reports the psycopsg2 error which I wanted to generate:

    
    
    [Tue Apr 19 13:09:53 2016] [error] Error when executing query SELECT [...] 
    [Tue Apr 19 13:09:53 2016] [error] column s.station_itgd does not exist 
    This is indeed the error I wanted to generate. 
    

The issue is that I thought my code would capture this error and then generate
a proper eror view. But this doesn't happen. I am aware that catching any
Exception is not a good practice - this is just the first step. Once I get the
response to work I will analyze which errors may occur and improve this part.


Answer: In a DRF view, you are always supposed to return a Response object. You could,
instead of raising a ParseError, ` from rest_framework import status return
Response({'detail':"Your error message"}, status=status.HTTP_400_BAD_REQUEST),
` Any uncatched exception will simply return
`Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)`

