10๐
โ
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"
}
๐คLukasz Dynowski
2๐
from rest_framework import exceptions
class ServiceUnavailableError(exceptions.APIException):
status_code = status.HTTP_503_SERVICE_UNAVAILABLE
default_detail = "Service unavailable."
# your views.py
raise ServiceUnavailableError("Override message.")
๐คuser1882644
- [Django]-Setting global variables with Cactus App for Mac
- [Django]-Django user proxy models fast access
- [Django]-Postgres with Django โ Improperly configured. Error : ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
- [Django]-Django autocomplete_fields doesn't work in TabularInline (but works in StackedInline)
- [Django]-How to pass args to a signal
1๐
You could use a simple function that return a dict:
def response_error_message(dic, message="An error occurred please try again later.", http_status=None):
dic["status_code"] = http_status or status.HTTP_500_INTERNAL_SERVER_ERROR
dic["object"] = message
dic["success"] = False
And the call in your view:
...
responsedic = {}
response_error_message(response_dic, message='Custom message', http_status=Custom_http_status)
return Response(response_dic)
๐คGocht
- [Django]-Pass a lazy translation string including variable to function in Django
- [Django]-Hiding save buttons in admin if all fields are read only
Source:stackexchange.com