django rest_framework custom exception error

  • Last Update :
  • Techknowledgy :

You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.,There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project.,The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.,The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view'].

For example, the following request:

DELETE http: //api.example.com/foo/bar HTTP/1.1
   Accept: application / json

Might receive an error response indicating that the DELETE method is not allowed on that resource:

HTTP / 1.1 405 Method Not Allowed
Content - Type: application / json
Content - Length: 42

{
   "detail": "Method 'DELETE' not allowed."
}

An example validation error might look like this:

HTTP / 1.1 400 Bad Request
Content - Type: application / json
Content - Length: 94

{
   "amount": ["A valid integer is required."],
   "description": ["This field may not be blank."]
}

In order to alter the style of the response, you could write the following custom exception handler:

from rest_framework.views
import exception_handler

def custom_exception_handler(exc, context):
   # Call REST framework 's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)

# Now add the HTTP status code to the response.
if response is not None:
   response.data['status_code'] = response.status_code

return response

The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example:

REST_FRAMEWORK = {
   'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

Suggestion : 2

First create exception handler which will handle errors for DRF:

# custom handler
from rest_framework.views
import exception_handler

def custom_exception_handler(exc, context):
   # Call REST framework 's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)

# Now add the HTTP status code to the response.
if response is not None:
   response.data['status_code'] = response.default_code

return response

Then update the settings.py with that error

# settings.py

REST_FRAMEWORK = {
   'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

Finally, create a custom exception and use that when you need to raise Catalog creation error:

# Custom exception

from rest_framework.exceptions
import APIException

class CatalogExeption(APIException):
   status_code = 503
default_detail = 'Unable to create catalog'
default_code = '4026'

In my case it would be something like this.

class ProductCatalogExeption(APIException):
   status_code = 200 #or whatever you want
default_code = '4026'
# Custom response below
default_detail = {
   "code": 4026,
   "message": "Unable to create catalog"
}

So when ProductCatalogException is raised it will return

{
   "code": 4026,
   "message": "Unable to create catalog"
}

Suggestion : 3

You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.,The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.,There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project.,Exceptions Exception handling in REST framework views Custom exception handling

DELETE http: //api.example.com/foo/bar HTTP/1.1
   Accept: application / json
HTTP / 1.1 405 Method Not Allowed
Content - Type: application / json
Content - Length: 42

{
   "detail": "Method 'DELETE' not allowed."
}
HTTP / 1.1 400 Bad Request
Content - Type: application / json
Content - Length: 94

{
   "amount": ["A valid integer is required."],
   "description": ["This field may not be blank."]
}
HTTP / 1.1 405 Method Not Allowed
Content - Type: application / json
Content - Length: 62

{
   "status_code": 405,
   "detail": "Method 'DELETE' not allowed."
}
from rest_framework.views
import exception_handler

def custom_exception_handler(exc, context):
   # Call REST framework 's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)

# Now add the HTTP status code to the response.
if response is not None:
   response.data['status_code'] = response.status_code

return response
REST_FRAMEWORK = {
   'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

Suggestion : 4

Posted on Aug 19, 2019 , Joined Dec 7, 2019 , Joined Jun 29, 2019 , Joined Dec 26, 2019

{
   'username': ['This field is required.'],
   'password': ['This field must be at least 8 chars'],
   'email': ['This field cannot be blank']
}
class UserSerializer(serializers.ModelSerializer):
   email = serializers.EmailField(required = True)
username = serializers.CharField(required = True)
password = serializers.CharField(min_length = 8, required = True)

class Meta:
   model = User
fields = ("id", "username", "email", "password")

def __init__(self, * args, ** kwargs):
   super(UserSerializer, self).__init__( * args, ** kwargs)
self.fields["username"].error_messages["required"] = u "username is required"
self.fields["username"].error_messages["blank"] = u "username cannot be blank"
self.fields["email"].error_messages["required"] = u "email is required"
self.fields["email"].error_messages["blank"] = u "email cannot be blank"
self.fields["password"].error_messages[
   "min_length"
] = u "password must be at least 8 chars"
from rest_framework.exceptions
import ValidationError
from rest_framework.views
import exception_handler

def base_exception_handler(exc, context):
   response = exception_handler(exc, context)

# check that a ValidationError exception is raised
if isinstance(exc, ValidationError):
   # here prepare the 'custom_error_response'
and
# set the custom response data on response object
if response.data.get("username", None):
   response.data = response.data["username"][0]
elif response.data.get("email", None):
   response.data = response.data["email"][0]
elif response.data.get("password", None):
   response.data = response.data["password"][0]

return response
REST_FRAMEWORK = {
   "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated", ),
   "DEFAULT_AUTHENTICATION_CLASSES": (
      "rest_framework.authentication.TokenAuthentication",
      "rest_framework.authentication.SessionAuthentication",
      "rest_framework.authentication.BasicAuthentication",
   ),
   "EXCEPTION_HANDLER": ("app.exceptions.base_exception_handler"),
}

Suggestion : 5

REST framework's views handle various exceptions, and deal with returning appropriate error responses.,In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.,Exception handling in REST framework views,Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.

For example, the following request:

DELETE http: //api.example.com/foo/bar HTTP/1.1
   Accept: application / json

Might receive an error response indicating that the DELETE method is not allowed on that resource:

HTTP / 1.1 405 Method Not Allowed
Content - Type: application / json;
charset = utf - 8
Content - Length: 42

{
   "detail": "Method 'DELETE' not allowed."
}