Skip to content

Provides request object into exception handler - #1671

Closed
pySilver wants to merge 3 commits into
encode:masterfrom
pySilver:improve-exception-handler
Closed

pySilver wants to merge 3 commits into
encode:masterfrom
pySilver:improve-exception-handler

Conversation

@pySilver

Copy link
Copy Markdown

This PR allows loggers such as Sentry get access to a request object constructed by the DRF using custom exception handler.

Problem was fully described here: #1380

@lovelydinosaur

Copy link
Copy Markdown
Member

Seems reasonable. Probably also needs some docs changes too?
Could you give an example case of how you could now fix up sentry logging using the custom exception handler?

@pySilver

pySilver commented Jul 1, 2014

Copy link
Copy Markdown
Author

@tomchristie sure here it is:

my settings.py :

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'core.exceptions.exception_handler',
}

my handler:

def exception_handler(exc, drf_request=None):
    """
    Replace request.POST with drf_request.DATA so Sentry
    can log request properly.

    @param exc: Exception
    @param drf_request: Request
    @return: None
    """
    response = views.exception_handler(exc)
    if response is None and drf_request is not None \
            and drf_request.method not in ['GET', 'HEAD', 'OPTIONS']:
        request = get_request()
        request.POST = drf_request.DATA

    return response

@kot-behemoth

Copy link
Copy Markdown

This looks precisely what I was looking for! Could you also supply the definition of get_request(), please? Also, you're not returning request, so how does that get propagated into the response?

@pySilver

Copy link
Copy Markdown
Author

@kot-behemoth take a look at original DRF exception handler.

@lovelydinosaur

Copy link
Copy Markdown
Member

Not happy with pushing the request object into the exception handling API. Just doesn't feel like the right thing to do. Yes it's awkward that request.DATA isn't available to sentry by default, yes it would be better if it was, but redesigning the exception handling API in order to support that use case doesn't seem to hit the design sweet spot.

Ideally we'd have request.data as a built-in feature in Django, but in the you'll need to look into other ways of handling this.

@pySilver

pySilver commented Nov 6, 2014

Copy link
Copy Markdown
Author

@tomchristie well this makes sentry and other logging apps useles. if there is no way to get a request data then the is no way for easy issues investigation :/ what is so wrong about configurable exception handler that have access to all possible information?

@lovelydinosaur

Copy link
Copy Markdown
Member

I'd be more interested for someone to investigate if this can instead be handled in, say, middleware in some sensible way. Yes, having request.data available to sentry would be hugely useful. Doesn't necessarily follow that we should alter the exception handling API as a kludgy workaround for making that possible.

@pySilver

pySilver commented Nov 6, 2014

Copy link
Copy Markdown
Author

well I've tried to do this functionality in a middleware, but I have a good way to do it without copying request object, which is bad idea

@lovelydinosaur

Copy link
Copy Markdown
Member

@pySilver Want to give an example of the bad way around of doing it - might be a starting point for us figuring out a decent way to support it with middleware without having to repurpose the exception handling API.

@lovelydinosaur

Copy link
Copy Markdown
Member

Reconsidering. See #2236.

@vesterbaek

Copy link
Copy Markdown

After #2236, you could do something ala

def exception_handler(exc, context):
    # Replace the POST data of the Django request with the parsed
    # data from the DRF
    # Necessary because we cannot read request data/stream more than once
    # This will allow us to see the parsed POST params in the rollbar exception log
    context['request']._request.POST = context['request'].data
    return views.exception_handler(exc, context)

@toxinu

toxinu commented Jan 6, 2016

Copy link
Copy Markdown

@vesterbaek workaround is far better than previous one.
But if you use DjangoDebugToolbar for example, it will use some methods like getlist (from django.http.request.QueryDict) on request instance that doesn't exist on context['request'].data because it's a dict.

You'll get this exception:

Traceback:
File "django/core/handlers/base.py" in get_response
  223. response = middleware_method(request, response)
File "debug_toolbar/middleware.py" in process_response
  94.  new_response = panel.process_response(request, response)
File "debug_toolbar/panels/request.py" in process_response
  31.  'post': [(k, request.POST.getlist(k)) for k in sorted(request.POST)],
File "debug_toolbar/panels/request.py" in <listcomp>
  31.  'post': [(k, request.POST.getlist(k)) for k in sorted(request.POST)],

Exception Type: AttributeError at /my-url
Exception Value: 'dict' object has no attribute 'getlist'

I used this workaround's workaround:

def exception_handler(exc, context):
    from rest_framework import views
    from django.http.request import QueryDict
    context['request']._request.POST = QueryDict(str(context['request'].data))
    return views.exception_handler(exc, context)

@pySilver

pySilver commented Jan 7, 2016

Copy link
Copy Markdown
Author

@socketubs, @vesterbaek original request.post won't be available the moment it's consumed, so you cannot substitute its later. And most importantly request.POST != request.data and it should not be.

@silviogutierrez

Copy link
Copy Markdown
Contributor

@socketubs : your approach worked, but the QueryDict was being represented as a big string inside outer brackets (on the sentry service). This approach kept it reading like a dictionary:

def exception_handler(exc, context):
    """
    See: https://github.com/tomchristie/django-rest-framework/pull/1671#issuecomment-169378632
    """
    from rest_framework import views
    from django.http.request import QueryDict
    query = QueryDict('', mutable=True)
    query.update(context['request'].data)
    context['request']._request.POST = query
    return views.exception_handler(exc, context)

@pySilver

pySilver commented Dec 6, 2016

Copy link
Copy Markdown
Author

@silviogutierrez it will fail if context['request'].data is a list (which is when ListSerializer or many=True is used).

@Hafnernuss Hafnernuss mentioned this pull request Mar 1, 2022
3 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

6 participants