[Solved]-How to add custom error codes to Django Rest Framework

7👍

I know this is a bit late, (better late than never).

If you have a structured error message, then try this by inheriting the Exception class

from rest_framework.serializers import ValidationError
from rest_framework import status


class CustomAPIException(ValidationError):
    status_code = status.HTTP_400_BAD_REQUEST
    default_code = 'error'

    def __init__(self, detail, status_code=None):
        self.detail = detail
        if status_code is not None:
            self.status_code = status_code

and the usage will be like this:

if some_condition:
    error_msg = {
        "error": True,
        "errors": [
            {
                "message": "Field %s does not exist"%('my_test_field'),
                "code": 1050
            }
        ]
    }
    raise CustomAPIException(error_msg)

Reference : How to override exception messages in django rest framework

👤JPG

4👍

This is my custom exception handler:

def api_exception_handler(exception, context):

    if isinstance(exception, exceptions.APIException):

        headers = {}

        if getattr(exception, 'auth_header', None):
            headers['WWW-Authenticate'] = exception.auth_header

        if getattr(exception, 'wait', None):
            headers['Retry-After'] = '%d' % exception.wait

        data = exception.get_full_details()
        set_rollback()

        return Response(data, status=exception.status_code, headers=headers)

    return exception_handler(exception, context)

It represents APIException errors in a format like this:

{
    "field_name": [
        {
            "message": "Error message",
            "code": "error_code"
        },
        {
            "message": "Another error",
            "code": "another_error"
        }
    ]
}

Django Rest Framework reference documentation:
http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

1👍

The exception handler is indeed what you’re looking for. The current mixing do raise an exception in case of failed validation (https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py).

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.

I think this part doesn’t hold any longer and should be rephrased by removing the “generic” word.

0👍

Alright so based on Linovia’s answer, here is my custom handler :

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response is not None:
        errors = []
        for msg in response.data.values():
            errors.append({'message': msg[0], 'error': get_error_message()})

        response.data = {"errors": errors}

    return response

Leave a comment