简体   繁体   中英

Django REST Custom Errors

I'm trying to create a custom error response from the REST Django framework.

I've included the following in my views.py ,

from rest_framework.views import exception_handler

def custom_exception_handler(exc):
    """
    Custom exception handler for Django Rest Framework that adds
    the `status_code` to the response and renames the `detail` key to `error`.
    """
    response = exception_handler(exc)

    if response is not None:
        response.data['status_code'] = response.status_code
        response.data['error'] = response.data['detail']
        response.data['detail'] = "CUSTOM ERROR"

    return response

And also added the following to settings.py .

REST_FRAMEWORK = {
              'DEFAULT_PERMISSION_CLASSES': (
                  'rest_framework.permissions.AllowAny',
              ),
              'EXCEPTION_HANDLER': 'project.input.utils.custom_exception_handler'
        }

Am I missing something as I don't get the expected response. ie a custom error message in the 400 API response.

Thanks,

As Bibhas said, with custom exception handlers, you only can return own defined errors when an exception is called. If you want to return a custom response error without exceptions being triggered, you need to return it in the view itself. For example:

    return Response({'detail' : "Invalid arguments", 'args' : ['arg1', 'arg2']}, 
                     status = status.HTTP_400_BAD_REQUEST)

From the documentation -

Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM