Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Getting Started

Exception Handling and Error Responses

Raise DRF exceptions such as NotFound and ValidationError, define your own APIException classes and write a custom exception handler for consistent error JSON.

Good APIs fail clearly. A client that sends a bad request should get a status code and a body that explain what went wrong, in the same shape every time. DRF does most of this through one idea: you raise an exception inside a view, and a handler turns it into a Response.

This lesson covers the built-in exceptions, how to define your own, which Django exceptions DRF converts automatically and how to install a custom handler so every error in the API shares one envelope.

Raising exceptions instead of building error responses

Compare two ways to say "no such book":

Python
# Manual
return Response({"detail": "Not found."}, status=404)

# Raising
raise NotFound("No book with that id.")

Raising has two advantages. It works from anywhere (a helper function, a serializer, a permission check), and it unwinds the stack immediately so you cannot forget a return.

All DRF exceptions inherit from rest_framework.exceptions.APIException. The common ones:

Exception Status Typical use
ValidationError 400 Bad input
ParseError 400 Malformed body
AuthenticationFailed, NotAuthenticated 401 or 403 Missing or bad credentials
PermissionDenied 403 Logged in but not allowed
NotFound 404 Missing resource
MethodNotAllowed 405 Wrong verb
NotAcceptable 406 No renderer for Accept
UnsupportedMediaType 415 No parser for Content-Type
Throttled 429 Too many requests
Python Raising the built-in exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every error body is JSON. A string message becomes {"detail": "..."}, while a dict (or list) passed to ValidationError is used as the body as it is. That is why field errors from serializers look like {"qty": [...]}.

Defining your own exception

Subclass APIException and set three class attributes: the status, a default message and a default code.

Python A custom APIException

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The code is a machine-readable string. Clients can switch on out_of_stock instead of parsing English. exc.detail is an ErrorDetail, a string subclass that carries the code.

What DRF converts for you

DRF's handler also catches two Django exceptions:

  • django.http.Http404 becomes a 404 with {"detail": "Not found."}.
  • django.core.exceptions.PermissionDenied becomes a 403.

This is why get_object_or_404(...) works inside API views. Anything else, such as a KeyError or a database error, is not handled: Django returns a 500 page. Do not catch broad exceptions to hide bugs; let them surface in your error monitoring.

A custom exception handler

The default handler returns inconsistent shapes: {"detail": ...} for most errors but a field dictionary for validation errors. Many teams prefer a single envelope. Write a function that calls the default handler, then reshapes its output, and register it with the EXCEPTION_HANDLER setting.

Python One error envelope for the whole API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The handler receives the exception and a context dictionary with the view, request, args and kwargs. Returning None means "I do not handle this", and Django's normal 500 processing takes over. In a real project the setting points to a module path such as "catalog.api.errors.envelope_handler"; here a small stand-in module called api_errors holds the function, so the path is api_errors.envelope_handler.

Log server-side problems inside the handler, and keep a stable code per error so apps released months ago keep working when you reword a message.

Errors from serializers

serializer.is_valid(raise_exception=True) raises ValidationError with the serializer's errors, so a view needs no manual if and no Response(serializer.errors, 400) branch. You will use this form in almost every view from here on.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does DRF do with an exception such as NotFound raised inside a view?

    The exception handler converts APIException subclasses into responses.
  2. 2. Which attributes define a custom APIException?

    Those three class attributes give the HTTP status, the default message and a machine-readable code.
  3. 3. What should a custom exception handler return for an exception it does not understand?

    DRF's exception_handler returns None for non-API exceptions; returning None passes them on to Django, which produces a 500.
  4. 4. Which setting installs your own handler?

    REST_FRAMEWORK = {'EXCEPTION_HANDLER': 'path.to.function'} registers it.

Summary

  • Raise APIException subclasses instead of hand-building error responses.
  • Built-ins cover 400, 401/403, 404, 405, 406, 415 and 429; Django's Http404 and PermissionDenied are converted too.
  • A custom exception needs status_code, default_detail and default_code.
  • A custom handler wraps DRF's exception_handler to give every error one shape.
  • Use serializer.is_valid(raise_exception=True) to skip manual error branches.

Next: Serializer Basics