Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw custom exception with custom error code on fly in django rest framework and override default fields in exception response

I would like to know how can I throw custom exception in django rest framework, that contains custom error_code and custom message. I am not interested in APIException() since this function does not allow for setting error code on fly. Additionally, I would like to know how to change the details key json response of exception message.

like image 240
Lukasz Dynowski Avatar asked Dec 15 '22 11:12

Lukasz Dynowski


1 Answers

I found the solution for all of my questions

api_exceptions.py

from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException

custom_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

        #replace detail key with message key by delete detail key
        response.data['message'] = response.data['detail']
        del response.data['detail']

    return response

CustomApiException

class CustomApiException(APIException):

    #public fields
    detail = None
    status_code = None

    # create constructor
    def __init__(self, status_code, message):
        #override public fields
        CustomApiException.status_code = status_code
        CustomApiException.detail = message

settings.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'utilities.helpers.api_exceptions.custom_exception_handler',
}

your_view.py

raise CustomApiException(333, "My custom message")

#json response
{
  "status_code": 333,
  "message": "My custom message"
}
like image 129
Lukasz Dynowski Avatar answered Apr 29 '23 18:04

Lukasz Dynowski