2

The default behaviour of DRF is to throw exception for 5XX, but return valid response with error details for 4XX. I want to log request and response of any API call which fails with 4XX.

Currently the log only shows Bad Request : /path/api/

Answer: Custom exception work fine.

1 Answer 1

2

You can define your own custom exception handler and access your request such as:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response is not None:
        response.data['status_code'] = response.status_code
        response.data['request'] = context['request']

    return response

And show your custom handler in settings.py such as:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
Sign up to request clarification or add additional context in comments.

Comments

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.