Error handling#

django-modern-rest has 3 layers where errors might be handled. It provides flexible error handling logic on Endpoint, Controller, and global levels.

All error handling functions always accept 3 arguments:

  1. Endpoint where error happened

  2. Controller where error happened

  3. Exception that happened

Here’s how it works:

  1. We first try to call error_handler that was passed into the endpoint definition via modify or validate

  2. If it returns django.http.HttpResponse, return it to the user

  3. If it raises an error, call handle_error() for sync controllers and handle_async_error() for async controllers with this raised error

  4. If controller’s handler returns HttpResponse, return it to the user

  5. If it raises an error, call configured global error handler with this raised error, by default it is global_error_handler() (it is always sync)

Warning

There are two things to keep in mind:

  1. Async endpoints will require async error_handler parameter, Sync endpoints will require sync error_handler parameter. This is validated on endpoint creation

  2. We don’t allow to define sync handle_error handlers for async controllers. We also don’t allow async handle_async_error handlers for sync controllers.

Note

APIError does not follow any of these rules and has a default handler, which will convert an instance of APIError to HttpResponse via to_error() call.

You don’t need to catch APIError in any way, unless you know what you are doing.

You can change the error instance that is handled during the error handling pipeline. For example:

  • Some YourCustomError happens in your endpoint

  • It is handled in a custom endpoint-level handler, which raises YourIntermediateError instead

  • Custom controller-level handler catches it and raises ValidationError instead

  • ValidationError is handled by the default global_error_handler() and returns an expected response

Customizing endpoint error handler#

Let’s pass custom error handling to a single endpoint:

Run result

$ curl http://127.0.0.1:8000/api/math/ -D - -X PATCH -d '{"left": 1, "right": 0}' -H 'Content-Type: application/json'
HTTP/1.1 400 Bad Request
date: Wed, 30 Sep 2026 23:18:48 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 39
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

{"detail":[{"msg":"division by zero"}]}

$ curl http://127.0.0.1:8000/api/math/ -D - -X POST -d '{"left": 1, "right": 0}' -H 'Content-Type: application/json'
HTTP/1.1 500 Internal Server Error
date: Wed, 30 Sep 2026 23:18:48 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 68
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

{"detail":[{"msg":"Internal server error","type":"internal_error"}]}

In this example we add error handling defined as division_error to patch endpoint, while keeping post endpoint without a custom error handler. So, the same request to post results in a default 500 response.

Per-endpoint’s error handling has a priority over per-controller and global handlers.

You can also define endpoint error handlers as controller methods and pass them wrapped with wrap_handler() as handlers. Like so:

Run result

$ curl http://127.0.0.1:8000/api/math/ -D - -X PATCH -d '{"left": 1, "right": 0}' -H 'Content-Type: application/json'
HTTP/1.1 400 Bad Request
date: Wed, 30 Sep 2026 23:18:49 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 39
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

{"detail":[{"msg":"division by zero"}]}

Customizing controller error handler#

Let’s create custom error handling for the whole controller:

In this example we are using zapros HTTP client to proxy an HTTP GET and POST requests to some other API service. If we fail to send a request and raise a specific HTTP client error, we return an error with 424 error code.

Going further#

Now you can understand how you can create:

  • Endpoints with custom error handlers

  • Controllers with custom error handlers

  • ResponseSpec objects for new error response schemas

You can dive even deeper and:

Error handling diagram#

The same error handling logic can be represented as a diagram:

        ---
config:
  theme: forest

---
graph TB
    Start[Request] --> Error{Error?};
    Error -->|Yes| Endpoint[Endpoint-level handler];
    Endpoint --> EndpointHandler{Raises or returns response?};
    EndpointHandler -->|response| Failure[Error response];
    EndpointHandler -->|raises| Controller[Controller-level handler];
    Controller --> ControllerHandler{Raises or returns response?};
    ControllerHandler -->|response| Failure[Error response];
    ControllerHandler -->|raises| Global[Global handler];
    Global --> GlobalHandler{Raises or returns response?};
    GlobalHandler -->|response| Failure[Error response];
    GlobalHandler -->|raises| Reraises[Reraises error];
    Error ---->|No| Success[Successful response];
    

Error handling logic#

Note

If Handling 500 errors is configured, it will catch all unhandled errors in the provided scope and return 500 errors with the correct payload.

Validating error responses#

Error responses are validated like any other response. With validate_responses enabled, only the status codes that you describe are allowed to be returned.

This matters the most for 500: we raise InternalServerError ourselves in several places, and your own code can raise it as well. An undescribed 500 will not reach the client, response validation will replace it with 422 Returned status code 500 is not specified.

Pick the way that matches how much you promise to your clients:

The strictest option: 500 becomes a part of your public contract.

It is listed in the OpenAPI schema, so clients can generate code for it and handle it in a typed way. Its body is still validated, so you cannot accidentally return something that does not match the schema.

Run result

$ curl http://127.0.0.1:8000/api/user/ -X POST -d '{"email": "user@wms.org"}' -H 'Content-Type: application/json'
{"email":"user@wms.org"}

$ curl http://127.0.0.1:8000/api/user/ -D - -X POST -d '{"email": "user@example.com"}' -H 'Content-Type: application/json'
HTTP/1.1 500 Internal Server Error
date: Wed, 30 Sep 2026 23:18:49 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 44
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

{"detail":[{"msg":"Internal server error"}]}

Use responses to do the same for the whole API at once:

settings.py#
>>> from http import HTTPStatus

>>> from dmr import ResponseSpec
>>> from dmr.errors import ErrorModel
>>> from dmr.settings import Settings

>>> DMR_SETTINGS = {
...     Settings.responses: [
...         ResponseSpec(
...             ErrorModel,
...             status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
...         ),
...     ],
... }

Added in version 0.15.0: exclude_validate_responses

Customizing error messages#

All error messages, including pre-defined ones, can be easily customized on a per-controller basis.

To do so, you would need to change:

  1. error_model attribute for all controllers that will be using this error message schema

  2. format_error() method to provide custom runtime error formatting

Run result

$ curl http://127.0.0.1:8000/api/example/ -X POST -d '{}' -H 'Content-Type: application/json'
{"errors":[{"message":"test msg"}]}

$ curl http://127.0.0.1:8000/api/example/ -X POST -d '[]' -H 'Content-Type: application/json'
{"errors":[{"message":"Input should be a valid dictionary"}]}

OpenAPI Schema

Preview openapi.json
{
  "components": {
    "schemas": {
      "CustomErrorDetail": {
        "properties": {
          "message": {
            "title": "Message",
            "type": "string"
          }
        },
        "required": [
          "message"
        ],
        "title": "CustomErrorDetail",
        "type": "object"
      },
      "CustomErrorModel": {
        "properties": {
          "errors": {
            "items": {
              "$ref": "#/components/schemas/CustomErrorDetail"
            },
            "title": "Errors",
            "type": "array"
          }
        },
        "required": [
          "errors"
        ],
        "title": "CustomErrorModel",
        "type": "object"
      }
    }
  },
  "info": {
    "title": "Django Modern Rest",
    "version": "0.1.0"
  },
  "openapi": "3.2.0",
  "paths": {
    "/api/apicontroller/": {
      "post": {
        "operationId": "postApiControllerApiApicontroller",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "Created"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CustomErrorModel"
                }
              }
            },
            "description": "Raised when request components cannot be parsed"
          },
          "402": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CustomErrorModel"
                }
              }
            },
            "description": "Payment Required"
          },
          "406": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CustomErrorModel"
                }
              }
            },
            "description": "Raised when provided `Accept` header cannot be satisfied"
          },
          "422": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CustomErrorModel"
                }
              }
            },
            "description": "Raised when returned response does not match the response schema"
          }
        }
      }
    }
  }
}

This will also change the OpenAPI schema for the affected controller.

See ErrorModel for the default error model schema. And format_error() for the default error formatting.

See content negotiation docs about how to use different error models for different content types.

But, there are more places that can have their own error schemas:

  1. build_csrf_handler() and CSRFSemanticSchemaProvider if you are using CSRF controllers

  2. build_404_handler() for default 404 responses

  3. build_500_handler() for default 500 responses

Customizing error headers and cookies#

Let’s say you want to customize how all errors responses behave and add a header, for example, X-Error-Id from your error tracking system.

How this can be done?

Run result

$ curl http://127.0.0.1:8000/api/example/ -X POST -d '{"key": "value"}' -H 'Content-Type: application/json'
{"key":"value"}

$ curl http://127.0.0.1:8000/api/example/ -D - -X POST -d '[]' -H 'Content-Type: application/json'
HTTP/1.1 400 Bad Request
date: Wed, 30 Sep 2026 23:18:51 GMT
server: uvicorn
X-Error-Id: Error-Id from your provider
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 100
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

{"detail":[{"msg":"Input should be a valid dictionary","loc":["parsed_body"],"type":"value_error"}]}

OpenAPI Schema

Preview openapi.json
{
  "components": {
    "schemas": {
      "ErrorDetail": {
        "description": "Base schema for error details description.",
        "properties": {
          "loc": {
            "items": {
              "anyOf": [
                {
                  "type": "integer"
                },
                {
                  "type": "string"
                }
              ]
            },
            "title": "Loc",
            "type": "array"
          },
          "msg": {
            "title": "Msg",
            "type": "string"
          },
          "type": {
            "title": "Type",
            "type": "string"
          }
        },
        "required": [
          "msg"
        ],
        "title": "ErrorDetail",
        "type": "object"
      },
      "ErrorModel": {
        "description": "Default error response schema.\n\nCan be customized.\nSee :ref:`customizing-error-messages` for more details.",
        "properties": {
          "detail": {
            "items": {
              "$ref": "#/components/schemas/ErrorDetail"
            },
            "title": "Detail",
            "type": "array"
          }
        },
        "required": [
          "detail"
        ],
        "title": "ErrorModel",
        "type": "object"
      }
    }
  },
  "info": {
    "title": "Django Modern Rest",
    "version": "0.1.0"
  },
  "openapi": "3.2.0",
  "paths": {
    "/api/apicontroller/": {
      "post": {
        "operationId": "postApiControllerApiApicontroller",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": {
                    "type": "string"
                  },
                  "type": "object"
                }
              }
            },
            "description": "Created"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              }
            },
            "description": "Raised when request components cannot be parsed",
            "headers": {
              "X-Error-Id": {
                "required": true,
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "406": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              }
            },
            "description": "Raised when provided `Accept` header cannot be satisfied",
            "headers": {
              "X-Error-Id": {
                "required": true,
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "422": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              }
            },
            "description": "Raised when returned response does not match the response schema",
            "headers": {
              "X-Error-Id": {
                "required": true,
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    }
  }
}

To attach response headers or cookies to the error model we use ResponseSpecMetadata inside typing.Annotated type.

We also have to redefine to_error() to add missing X-Error-Id headers for your error responses.

You can do the same for all responses, not just failing ones. For this, override to_response().

This can also be used to attach RateLimit headers and other Throttling information.

Headers and cookies of union responses#

A single response can be a union of several models, and ResponseSpecMetadata can be placed on the union or on any of its members. Where you put it changes what you promise:

Run result

$ curl http://127.0.0.1:8000/api/example/ -D - -X POST -d '{"username": "sobolevn"}' -H 'Content-Type: application/json'
HTTP/1.1 201 Created
date: Wed, 30 Sep 2026 23:18:52 GMT
server: uvicorn
X-User-Id: User-Id from your database
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 23
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

{"username":"sobolevn"}

$ curl http://127.0.0.1:8000/api/example/ -D - -X POST -d '{}' -H 'Content-Type: application/json'
HTTP/1.1 201 Created
date: Wed, 30 Sep 2026 23:18:52 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 11
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

"anonymous"

OpenAPI Schema

Preview openapi.json
{
  "components": {
    "schemas": {
      "ErrorDetail": {
        "description": "Base schema for error details description.",
        "properties": {
          "loc": {
            "items": {
              "anyOf": [
                {
                  "type": "integer"
                },
                {
                  "type": "string"
                }
              ]
            },
            "title": "Loc",
            "type": "array"
          },
          "msg": {
            "title": "Msg",
            "type": "string"
          },
          "type": {
            "title": "Type",
            "type": "string"
          }
        },
        "required": [
          "msg"
        ],
        "title": "ErrorDetail",
        "type": "object"
      },
      "ErrorModel": {
        "description": "Default error response schema.\n\nCan be customized.\nSee :ref:`customizing-error-messages` for more details.",
        "properties": {
          "detail": {
            "items": {
              "$ref": "#/components/schemas/ErrorDetail"
            },
            "title": "Detail",
            "type": "array"
          }
        },
        "required": [
          "detail"
        ],
        "title": "ErrorModel",
        "type": "object"
      },
      "User": {
        "properties": {
          "username": {
            "title": "Username",
            "type": "string"
          }
        },
        "required": [
          "username"
        ],
        "title": "User",
        "type": "object"
      }
    }
  },
  "info": {
    "title": "Django Modern Rest",
    "version": "0.1.0"
  },
  "openapi": "3.2.0",
  "paths": {
    "/api/apicontroller/": {
      "post": {
        "operationId": "postApiControllerApiApicontroller",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/User"
                    },
                    {
                      "type": "string"
                    }
                  ]
                }
              }
            },
            "description": "Created",
            "headers": {
              "X-User-Id": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              }
            },
            "description": "Raised when request components cannot be parsed"
          },
          "406": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              }
            },
            "description": "Raised when provided `Accept` header cannot be satisfied"
          },
          "422": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              }
            },
            "description": "Raised when returned response does not match the response schema"
          }
        }
      }
    }
  }
}

Here only User responses carry X-User-Id, a str response is returned without it. Since one response has one set of specs, we document X-User-Id as required=False: it can be missing, so we don’t validate that it is always there.

Annotate the whole union instead when every response has the header:

>>> from typing import Annotated

>>> from dmr import HeaderSpec
>>> from dmr.metadata import ResponseSpecMetadata

>>> AlwaysIdentified = Annotated[
...     str | int,
...     ResponseSpecMetadata(headers={'X-User-Id': HeaderSpec()}),
... ]

Now X-User-Id is required for both str and int responses, and a response without it fails validation.

The same rule applies when several members are annotated: a header is required only when every member of the union declares it as required. Specs of all members end up in the documentation either way.

Warning

Do not design new APIs this way.

One response with one status code should always have the same set of required headers and cookies. When it does not, every client has to inspect the body first to learn which headers it is allowed to read, and the OpenAPI schema cannot express that dependency at all: it only says the header is optional.

We support per-member metadata for legacy code and migrations, where a response already behaves like this and the behaviour cannot be changed yet. For new endpoints, annotate the whole union, or split the response into separate status codes.

Changed in version 0.16.0: Metadata of union members used to be ignored completely.

Problem Details#

django-modern-rest supports customizing of all error message inside the framework, including builtin ones.

ProblemDetailsError is a great example of how it can be done.

It is a regular subclass of APIError, which does not have any special handling inside our framework. This is done on purpose, so we can be sure that users also can to customize their exceptions any way they need.

We support two main use-cases for Problem Details.

Always raising Problem Details#

To always use ProblemDetailsError inside your controller you would need to:

  1. Define error_model attribute as ProblemDetailsModel

  2. Raise an exception itself, pass all the required fields

  3. Convert other message to the Problem Details format using format_error() method

Run result

$ curl http://127.0.0.1:8000/api/balance/ -X GET
{"detail":"Your current balance is 0, but the price is 15","status":402,"type":"https://example.com/probs/out-of-credit","title":"Not enough funds","instance":"/account/users/1/","balance":0,"price":15}

$ curl 'http://127.0.0.1:8000/api/balance/?number=a' -X GET
{"detail":"Input should be a valid integer, unable to parse string as an integer","status":400,"type":"value_error","title":"From format_error"}

OpenAPI Schema

Preview openapi.json
{
  "components": {
    "schemas": {
      "ProblemDetailsModel": {
        "description": "Error payload model for Problem Details.\n\nSee https://datatracker.ietf.org/doc/html/rfc9457\nfor the detailed description of each field.",
        "properties": {
          "detail": {
            "title": "Detail",
            "type": "string"
          },
          "instance": {
            "title": "Instance",
            "type": "string"
          },
          "status": {
            "title": "Status",
            "type": "integer"
          },
          "title": {
            "title": "Title",
            "type": "string"
          },
          "type": {
            "title": "Type",
            "type": "string"
          }
        },
        "title": "ProblemDetailsModel",
        "type": "object"
      }
    }
  },
  "info": {
    "title": "Django Modern Rest",
    "version": "0.1.0"
  },
  "openapi": "3.2.0",
  "paths": {
    "/api/problemdetailscontroller/": {
      "get": {
        "operationId": "getProblemDetailsControllerApiProblemdetailscontroller",
        "parameters": [
          {
            "in": "query",
            "name": "number",
            "schema": {
              "default": 0,
              "title": "Number",
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "OK"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetailsModel"
                }
              }
            },
            "description": "Raised when request components cannot be parsed"
          },
          "402": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetailsModel"
                }
              }
            },
            "description": "Payment Required"
          },
          "406": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetailsModel"
                }
              }
            },
            "description": "Raised when provided `Accept` header cannot be satisfied"
          },
          "422": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetailsModel"
                }
              }
            },
            "description": "Raised when returned response does not match the response schema"
          }
        }
      }
    }
  }
}

Conditionally raising Problem Details#

Another way is to negotiate the error response format. How does it work?

  1. When user sends a request with Accept header with application/problem+json content type, we will return Problem Details errors

  2. When application/json or any other content type is sent, we return regular ErrorModel error payloads

To do so, you would need a slightly more difficult setup:

  1. Define error_model attribute as the result of error_model() method call. It will add conditional schema types to your error responses

  2. Define several Renderer types, including the one which will handle application/problem+json

  3. Raise a conditional exception: use conditional_error() to only raise Problem Details when the correct accepted type is passed

  4. Convert other message to the Problem Details format using format_error() method when the correct accepted type is passed

Run result

$ curl http://127.0.0.1:8000/api/balance/ -X GET
{"detail":[{"msg":"Your current balance is 0, but the price is 15","type":"https://example.com/probs/out-of-credit"}]}

$ curl http://127.0.0.1:8000/api/balance/ -X GET -H 'Accept: application/problem+json'
{"detail":"Your current balance is 0, but the price is 15","status":402,"type":"https://example.com/probs/out-of-credit","title":"Not enough funds","instance":"/account/users/1/","balance":0,"price":15}

OpenAPI Schema

Preview openapi.json
{
  "components": {
    "schemas": {
      "ErrorDetail": {
        "description": "Base schema for error details description.",
        "properties": {
          "loc": {
            "items": {
              "anyOf": [
                {
                  "type": "integer"
                },
                {
                  "type": "string"
                }
              ]
            },
            "title": "Loc",
            "type": "array"
          },
          "msg": {
            "title": "Msg",
            "type": "string"
          },
          "type": {
            "title": "Type",
            "type": "string"
          }
        },
        "required": [
          "msg"
        ],
        "title": "ErrorDetail",
        "type": "object"
      },
      "ErrorModel": {
        "description": "Default error response schema.\n\nCan be customized.\nSee :ref:`customizing-error-messages` for more details.",
        "properties": {
          "detail": {
            "items": {
              "$ref": "#/components/schemas/ErrorDetail"
            },
            "title": "Detail",
            "type": "array"
          }
        },
        "required": [
          "detail"
        ],
        "title": "ErrorModel",
        "type": "object"
      },
      "ProblemDetailsModel": {
        "description": "Error payload model for Problem Details.\n\nSee https://datatracker.ietf.org/doc/html/rfc9457\nfor the detailed description of each field.",
        "properties": {
          "detail": {
            "title": "Detail",
            "type": "string"
          },
          "instance": {
            "title": "Instance",
            "type": "string"
          },
          "status": {
            "title": "Status",
            "type": "integer"
          },
          "title": {
            "title": "Title",
            "type": "string"
          },
          "type": {
            "title": "Type",
            "type": "string"
          }
        },
        "title": "ProblemDetailsModel",
        "type": "object"
      }
    }
  },
  "info": {
    "title": "Django Modern Rest",
    "version": "0.1.0"
  },
  "openapi": "3.2.0",
  "paths": {
    "/api/problemdetailscontroller/": {
      "get": {
        "operationId": "getProblemDetailsControllerApiProblemdetailscontroller",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "string"
                }
              },
              "application/problem+json": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "OK"
          },
          "402": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetailsModel"
                }
              }
            },
            "description": "Payment Required"
          },
          "406": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetailsModel"
                }
              }
            },
            "description": "Raised when provided `Accept` header cannot be satisfied"
          },
          "422": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorModel"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetailsModel"
                }
              }
            },
            "description": "Raised when returned response does not match the response schema"
          }
        }
      }
    }
  }
}

Tip

You can still make application/problem+json the default and when application/json (or any other type) is explicitly requested return the ErrorModel errors.

Handling validation errors from models#

When creating models with, for example, pydantic.BaseModel, your validation can fail. This error will not be handled by design.

Why? Because catching all specific validation errors for a specific serializer that can happen in your application will do more harm than good.

This is the default behavior:

Run result

$ curl http://127.0.0.1:8000/api/ping/ -D - -X GET
HTTP/1.1 500 Internal Server Error
date: Wed, 30 Sep 2026 23:18:54 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 68
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

{"detail":[{"msg":"Internal server error","type":"internal_error"}]}

If you want to catch this error in a specific place and attach a specific behavior, use an error handler at a proper level.

For example, here we would handle it on a controller level:

Run result

$ curl http://127.0.0.1:8000/api/ping/ -D - -X GET
HTTP/1.1 500 Internal Server Error
date: Wed, 30 Sep 2026 23:18:54 GMT
server: uvicorn
Content-Type: application/json
X-Frame-Options: DENY
Vary: Accept-Language
Content-Language: en
Content-Length: 39
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

{"detail":[{"msg":"Validation error"}]}

Now, the error is handled: we modified its error text and status code. Remember not to dump all the error information out to users, since they might contain sensitive data.

See also

See Handling 500 errors if you want to change the 500 error rendering.

API Reference#

dmr.errors.global_error_handler(endpoint: Endpoint, controller: Controller[BaseSerializer], exc: Exception) → HttpResponse[source]#

Global error handler for all cases.

It is the last item in the chain that we try:

  1. Per endpoint configuration via handle_error() and handle_async_error() methods

  2. Per controller handlers

  3. This global handler, specified via the configuration

If some exception cannot be handled, it is just reraised.

Parameters:
  • endpoint – Endpoint where error happened.

  • controller – Controller instance that endpoint belongs to.

  • exc – Exception instance that happened.

Returns:

HttpResponse with proper response for this error. Or raise exc back.

Here’s an example that will produce {'detail': [{'msg': 'inf', 'type': 'user_msg'}]} for any ZeroDivisionError in your application:

>>> from http import HTTPStatus
>>> from django.http import HttpResponse
>>> from dmr.controller import Controller
>>> from dmr.endpoint import Endpoint
>>> from dmr.errors import global_error_handler, ErrorType

>>> def custom_error_handler(
...     controller: Controller,
...     endpoint: Endpoint,
...     exc: Exception,
... ) -> HttpResponse:
...     if isinstance(exc, ZeroDivisionError):
...         return controller.to_error(
...             controller.format_error(
...                 'inf',
...                 error_type=ErrorType.user_msg,
...             ),
...             status_code=HTTPStatus.NOT_IMPLEMENTED,
...         )
...     # Call the original handler to handle default errors:
...     return global_error_handler(controller, endpoint, exc)

>>> # And then in your settings file:
>>> DMR_SETTINGS = {
...     # Object `custom_error_handler` will also work:
...     'global_error_handler': 'path.to.custom_error_handler',
... }

Warning

Make sure you always call original global_error_handler in the very end. Unless, you want to disable original error handling.

dmr.errors.wrap_handler(method: _MethodSyncHandler) → SyncErrorHandler[source]#
dmr.errors.wrap_handler(method: _MethodAsyncHandler) → AsyncErrorHandler

Utility function to wrap controller methods.

It is used to wrap an existing controller method and pass it as error_handler= argument to an endpoint.

final class dmr.errors.ErrorType(*values)[source]#

Collection of all possible error types that we use in DMR.

value_error#

Raised when we can’t parse something.

internal_error#

Raised when internal error happens.

not_allowed#

Raised when using unsupported http method. 405 alias.

security#

Raised when security related error happens.

ratelimit#

Raised when ratelimit related error happens.

user_msg#

Raised for custom errors from users.

not_found#

Raised when we can’t find controller.

streaming#

Happens when we stream events.

class dmr.errors.ErrorModel[source]#

Bases: TypedDict

Default error response schema.

Can be customized. See Customizing error messages for more details.

class dmr.errors.ErrorDetail[source]#

Bases: TypedDict

Base schema for error details description.

msg: str#

Optional error type identifier.

type: NotRequired[str]#

Optional location where this error happened.

dmr.errors.format_error(error: str | Exception, *, loc: str | list[str | int] | None = None, error_type: str | ErrorType | None = None) → ErrorModel[source]#

Convert error to the common format.

Default implementation.

Parameters:
  • error – A serialization exception like a validation error.

  • loc – Location where this error happened. Like "headers", or "field_name", or ["parsed_headers", "header_name"].

  • error_type – Optional type of the error for extra metadata.

Returns:

Simple python object - exception converted to a common format.

Problem Details API#

class dmr.problem_details.ProblemDetailsError(detail: str, *, status_code: HTTPStatus, type: str | None = None, title: str | None = None, instance: str | None = None, extra: Mapping[str, Any] | None = None, headers: Mapping[str, str] | None = None, cookies: Mapping[str, NewCookie] | None = None, show_status: bool = True, show_detail: bool = True)[source]#

Bases: APIError[ProblemDetailsModel]

Problem Details exception.

It is a subclass of dmr.response.APIError, so you can raise it anywhere in the REST part of your app.

There are two major use-cases that we support for this class:

  1. Direct usage: you raise an error and get what you raise, no changes

  2. Conditional usage: you call conditional_error method and if the client accepts application/problem+json, we will return the proper Problem Details description. But, if it is not requested directly, we will return our regular dmr.errors.ErrorModel

Both use-cases are independent. You can decide what to use per controller.

classmethod conditional_error(detail: str, *, status_code: HTTPStatus, controller: Controller[BaseSerializer], type: str | None = None, title: str | None = None, instance: str | None = None, extra: Mapping[str, Any] | None = None, headers: Mapping[str, str] | None = None, cookies: Mapping[str, NewCookie] | None = None, show_status: bool = True, show_detail: bool = True) → APIError[Any][source]#

Create conditional error.

If request accepts application/problem+json then return a Problem Details exception. If not, return regular dmr.response.APIError instance.

Otherwise, returns regular error from controller using its format_error() method for formatting.

classmethod error_model(existing_errors: Mapping[str, Any], content_type: str | None = None) → Any[source]#

Builds an error model for conditional responses.

Only use this method when you use conditional_error. If you are using regular exceptions, use ProblemDetailsModel directly.

classmethod format_error(error: str | Exception, *, loc: str | list[str | int] | None = None, error_type: str | ErrorType | None = None, status_code: HTTPStatus | None = None, title: str | None = None, instance: str | None = None, extra: Mapping[str, Any] | None = None) → ErrorModel | ProblemDetailsModel[source]#

Format other errors to be in format of Problem Details.

problem_details_model#

alias of ProblemDetailsModel

class dmr.problem_details.ProblemDetailsModel[source]#

Error payload model for Problem Details.

See https://datatracker.ietf.org/doc/html/rfc9457 for the detailed description of each field.