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:
Endpointwhere error happenedControllerwhere error happenedException that happened
Here’s how it works:
We first try to call
error_handlerthat was passed into the endpoint definition viamodify()orvalidate()If it returns
django.http.HttpResponse, return it to the userIf it raises, call
handle_error()for sync controllers andhandle_async_error()for async controllersIf controller’s handler returns
HttpResponse, return it to the userIf it raises, call configured global error handler, by default it is
global_error_handler()(it is always sync)
Warning
There are two things to keep in mind:
Async endpoints will require async
error_handlerparameter, Sync endpoints will require syncerror_handlerparameter. This is validated on endpoint creationWe don’t allow to define sync
handle_errorhandlers for async controllers. We also don’t allow asynchandle_async_errorhandlers 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.
Customizing endpoint error handler¶
Let’s pass custom error handling to a single endpoint:
1from http import HTTPStatus
2
3import pydantic
4from django.http import HttpResponse
5
6from dmr import Body, Controller, modify
7from dmr.endpoint import Endpoint
8from dmr.plugins.pydantic import PydanticSerializer
9from dmr.serializer import BaseSerializer
10
11
12class TwoNumbers(pydantic.BaseModel):
13 left: int
14 right: int
15
16
17def division_error( # <- we define an error handler
18 endpoint: Endpoint,
19 controller: Controller[BaseSerializer],
20 exc: Exception,
21) -> HttpResponse:
22 if isinstance(exc, ZeroDivisionError):
23 # This response's schema was automatically added by `Body`:
24 return controller.to_error(
25 controller.format_error(str(exc)),
26 status_code=HTTPStatus.BAD_REQUEST,
27 )
28 # Reraise unfamiliar errors to let someone
29 # else to handle them further.
30 raise exc from None
31
32
33class MathController(Controller[PydanticSerializer]):
34 @modify(error_handler=division_error) # <- and we pass the handler
35 def patch(
36 self,
37 parsed_body: Body[TwoNumbers],
38 ) -> float: # <- has custom error handling
39 return parsed_body.left / parsed_body.right
40
41 def post(
42 self,
43 parsed_body: Body[TwoNumbers],
44 ) -> float: # <- has only default error handling
45 return parsed_body.left / parsed_body.right
46
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: Thu, 09 Apr 2026 14:41:26 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: Thu, 09 Apr 2026 14:41:27 GMT
server: uvicorn
Content-Type: text/html; charset=utf-8
X-Frame-Options: DENY
Vary: Accept-Language, Cookie
Content-Language: en
Content-Length: 99794
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE">
<title>ZeroDivisionError
at /api/math/</title>
<style>
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font-family: sans-serif; background-color:#fff; color:#000; }
body > :where(header, main, footer) { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; }
h2 { margin-bottom:.8em; }
h3 { margin:1em 0 .5em 0; }
h4 { margin:0 0 .5em 0; font-weight: normal; }
code, pre { font-size: 100%; white-space: pre-wrap; word-break: break-word; }
summary { cursor: pointer; }
table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
tbody td, tbody th { vertical-align:top; padding:2px 3px; }
thead th {
padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
font-weight:normal; font-size: 0.6875rem; border:1px solid #ddd;
}
tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
table.vars { margin:5px 10px 2px 40px; width: auto; }
table.vars td, table.req td { font-family:monospace; }
table td.code { width:100%; }
table td.code pre { overflow:hidden; }
table.source th { color:#666; }
table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
ul.traceback { list-style-type:none; color: #222; }
ul.traceback li.cause { word-break: break-word; }
ul.traceback li.frame { padding-bottom:1em; color:#4f4f4f; }
ul.traceback li.user { background-color:#e0e0e0; color:#000 }
div.context { padding:10px 0; overflow:hidden; }
div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; }
div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; padding-left: 2px; }
div.context ol li pre { display:inline; }
div.context ol.context-line li { color:#464646; background-color:#dfdfdf; padding: 3px 2px; }
div.context ol.context-line li span { position:absolute; right:32px; }
.user div.context ol.context-line li { background-color:#bbb; color:#000; }
.user div.context ol li { color:#666; }
div.commands, summary.commands { margin-left: 40px; }
div.commands a, summary.commands { color:#555; text-decoration:none; }
.user div.commands a { color: black; }
#summary { background: #ffc; }
#summary h2 { font-weight: normal; color: #666; }
#info { padding: 0; }
#info > * { padding:10px 20px; }
#explanation { background:#eee; }
#template, #template-not-exist { background:#f6f6f6; }
#template-not-exist ul { margin: 0 0 10px 20px; }
#template-not-exist .postmortem-section { margin-bottom: 3px; }
#unicode-hint { background:#eee; }
#traceback { background:#eee; }
#requestinfo { background:#f6f6f6; padding-left:120px; }
#summary table { border:none; background:transparent; }
#requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
#requestinfo h3 { margin-bottom:-1em; }
.error { background: #ffc; }
.specific { color:#cc3300; font-weight:bold; }
h2 span.commands { font-size: 0.7rem; font-weight:normal; }
span.commands a:link {color:#5E5694;}
pre.exception_value { font-family: sans-serif; color: #575757; font-size: 1.5rem; margin: 10px 0 10px 0; }
.append-bottom { margin-bottom: 10px; }
.fname { user-select: all; }
</style>
<script>
function hideAll(elems) {
for (var e = 0; e < elems.length; e++) {
elems[e].style.display = 'none';
}
}
window.onload = function() {
hideAll(document.querySelectorAll('ol.pre-context'));
hideAll(document.querySelectorAll('ol.post-context'));
hideAll(document.querySelectorAll('div.pastebin'));
}
function toggle() {
for (var i = 0; i < arguments.length; i++) {
var e = document.getElementById(arguments[i]);
if (e) {
e.style.display = e.style.display == 'none' ? 'block': 'none';
}
}
return false;
}
function switchPastebinFriendly(link) {
s1 = "Switch to copy-and-paste view";
s2 = "Switch back to interactive view";
link.textContent = link.textContent.trim() == s1 ? s2: s1;
toggle('browserTraceback', 'pastebinTraceback');
return false;
}
</script>
</head>
<body>
<header id="summary">
<h1>ZeroDivisionError
at /api/math/</h1>
<pre class="exception_value">division by zero</pre>
<table class="meta">
<tr>
<th scope="row">Request Method:</th>
<td>POST</td>
</tr>
<tr>
<th scope="row">Request URL:</th>
<td>http://127.0.0.1:52227/api/math/</td>
</tr>
<tr>
<th scope="row">Django Version:</th>
<td>5.2.13</td>
</tr>
<tr>
<th scope="row">Exception Type:</th>
<td>ZeroDivisionError</td>
</tr>
<tr>
<th scope="row">Exception Value:</th>
<td><pre>division by zero</pre></td>
</tr>
<tr>
<th scope="row">Exception Location:</th>
<td><span class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/docs/examples/error_handling/endpoint.py</span>, line 45, in post</td>
</tr>
<tr>
<th scope="row">Raised during:</th>
<td>examples.error_handling.endpoint.MathController</td>
</tr>
<tr>
<th scope="row">Python Executable:</th>
<td>/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/bin/python</td>
</tr>
<tr>
<th scope="row">Python Version:</th>
<td>3.12.10</td>
</tr>
<tr>
<th scope="row">Python Path:</th>
<td><pre><code>['/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0',
'/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/django_test_app',
'/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/docs',
'/home/docs/.asdf/installs/python/3.12.10/lib/python312.zip',
'/home/docs/.asdf/installs/python/3.12.10/lib/python3.12',
'/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/lib-dynload',
'/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages']</code></pre></td>
</tr>
<tr>
<th scope="row">Server time:</th>
<td>Thu, 09 Apr 2026 09:41:27 -0500</td>
</tr>
</table>
</header>
<main id="info">
<div id="traceback">
<h2>Traceback <span class="commands"><a href="#" role="button" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>
</h2>
<div id="browserTraceback">
<ul class="traceback">
<li class="frame django">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/core/handlers/exception.py</code>, line 42, in inner
<div class="context" id="c133853719135808">
<ol start="35" class="pre-context" id="pre133853719135808">
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> can rely on getting a response instead of an exception.</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> """</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> if iscoroutinefunction(get_response):</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre></pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> @wraps(get_response)</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> async def inner(request):</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> try:</pre></li>
</ol>
<ol start="42" class="context-line">
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> response = await get_response(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='43' class="post-context" id="post133853719135808">
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> except Exception as exc:</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> response = await sync_to_async(</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> response_for_exception, thread_sensitive=False</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> )(request, exc)</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre> return response</pre></li>
<li onclick="toggle('pre133853719135808', 'post133853719135808')"><pre></pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719135808">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>exc</td>
<td class="code"><pre>ZeroDivisionError('division by zero')</pre></td>
</tr>
<tr>
<td>get_response</td>
<td class="code"><pre><bound method BaseHandler._get_response_async of <django.core.handlers.asgi.ASGIHandler object at 0x79bd3f9193d0>></pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: POST '/api/math/'></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame django">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/core/handlers/base.py</code>, line 253, in _get_response_async
<div class="context" id="c133853719135360">
<ol start="246" class="pre-context" id="pre133853719135360">
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> wrapped_callback = self.make_view_atomic(callback)</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> # If it is a synchronous view, run it in a subthread</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> if not iscoroutinefunction(wrapped_callback):</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> wrapped_callback = sync_to_async(</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> wrapped_callback, thread_sensitive=True</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> )</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> try:</pre></li>
</ol>
<ol start="253" class="context-line">
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> response = await wrapped_callback(
</pre> <span>…</span></li>
</ol>
<ol start='254' class="post-context" id="post133853719135360">
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> request, *callback_args, **callback_kwargs</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> )</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> except Exception as e:</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> response = await sync_to_async(</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> self.process_exception_by_middleware,</pre></li>
<li onclick="toggle('pre133853719135360', 'post133853719135360')"><pre> thread_sensitive=True,</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719135360">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>callback</td>
<td class="code"><pre><function View.as_view.<locals>.view at 0x79bd3fd23f60></pre></td>
</tr>
<tr>
<td>callback_args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>callback_kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>middleware_method</td>
<td class="code"><pre><asgiref.sync.SyncToAsync object at 0x79bd3fad7020></pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: POST '/api/math/'></pre></td>
</tr>
<tr>
<td>response</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><django.core.handlers.asgi.ASGIHandler object at 0x79bd3f9193d0></pre></td>
</tr>
<tr>
<td>wrapped_callback</td>
<td class="code"><pre><asgiref.sync.SyncToAsync object at 0x79bd3fae64b0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/concurrent/futures/thread.py</code>, line 59, in run
<div class="context" id="c133853719135232">
<ol start="52" class="pre-context" id="pre133853719135232">
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> self.kwargs = kwargs</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre></pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> def run(self):</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> if not self.future.set_running_or_notify_cancel():</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> return</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre></pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> try:</pre></li>
</ol>
<ol start="59" class="context-line">
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='60' class="post-context" id="post133853719135232">
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> except BaseException as exc:</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> self.future.set_exception(exc)</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> # Break a reference cycle with the exception 'exc'</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> self = None</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> else:</pre></li>
<li onclick="toggle('pre133853719135232', 'post133853719135232')"><pre> self.future.set_result(result)</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719135232">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>self</td>
<td class="code"><pre>None</pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame django">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/views/decorators/csrf.py</code>, line 65, in _view_wrapper
<div class="context" id="c133853719135104">
<ol start="58" class="pre-context" id="pre133853719135104">
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre></pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre> async def _view_wrapper(request, *args, **kwargs):</pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre> return await view_func(request, *args, **kwargs)</pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre></pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre> else:</pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre></pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre> def _view_wrapper(request, *args, **kwargs):</pre></li>
</ol>
<ol start="65" class="context-line">
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre> return view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='66' class="post-context" id="post133853719135104">
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre></pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre> _view_wrapper.csrf_exempt = True</pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre></pre></li>
<li onclick="toggle('pre133853719135104', 'post133853719135104')"><pre> return wraps(view_func)(_view_wrapper)</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719135104">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: POST '/api/math/'></pre></td>
</tr>
<tr>
<td>view_func</td>
<td class="code"><pre><function View.as_view.<locals>.view at 0x79bd3fd23d80></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame django">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/views/generic/base.py</code>, line 105, in view
<div class="context" id="c133853723712832">
<ol start="98" class="pre-context" id="pre133853723712832">
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> self = cls(**initkwargs)</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> self.setup(request, *args, **kwargs)</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> if not hasattr(self, "request"):</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> raise AttributeError(</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> "%s instance has no 'request' attribute. Did you override "</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> "setup() and forget to call super()?" % cls.__name__</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> )</pre></li>
</ol>
<ol start="105" class="context-line">
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='106' class="post-context" id="post133853723712832">
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre></pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> view.view_class = cls</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> view.view_initkwargs = initkwargs</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre></pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> # __name__ and __qualname__ are intentionally left unchanged as</pre></li>
<li onclick="toggle('pre133853723712832', 'post133853723712832')"><pre> # view_class should be used to robustly determine the name of the view</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853723712832">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>cls</td>
<td class="code"><pre><class 'examples.error_handling.endpoint.MathController'></pre></td>
</tr>
<tr>
<td>initkwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: POST '/api/math/'></pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/controller.py</code>, line 224, in dispatch
<div class="context" id="c133853719134912">
<ol start="217" class="pre-context" id="pre133853719134912">
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre></pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> Return 405 if this method is not allowed.</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> """</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> # Fast path for method resolution:</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> method: str = request.method # type: ignore[assignment]</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> endpoint = self.api_endpoints.get(method)</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> if endpoint is not None:</pre></li>
</ol>
<ol start="224" class="context-line">
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> return endpoint(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='225' class="post-context" id="post133853719134912">
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> # This return is very special,</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> # since it does not have an attached endpoint.</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> # All other responses are handled on endpoint level</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> # with all the response type validation.</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre> return self.handle_method_not_allowed(method)</pre></li>
<li onclick="toggle('pre133853719134912', 'post133853719134912')"><pre></pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719134912">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>endpoint</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>method</td>
<td class="code"><pre>'POST'</pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: POST '/api/math/'></pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 183, in __call__
<div class="context" id="c133853719134784">
<ol start="176" class="pre-context" id="pre133853719134784">
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> def __call__(</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> controller: 'Controller[BaseSerializer]',</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> *args: Any,</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> **kwargs: Any,</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> ) -> HttpResponseBase:</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> """Run the endpoint and return the response."""</pre></li>
</ol>
<ol start="183" class="context-line">
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> return self._func( # type: ignore[no-any-return]
</pre> <span>…</span></li>
</ol>
<ol start='184' class="post-context" id="post133853719134784">
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> controller,</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> *args,</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> **kwargs,</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> )</pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre></pre></li>
<li onclick="toggle('pre133853719134784', 'post133853719134784')"><pre> def handle_error(</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719134784">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 383, in decorator
<div class="context" id="c133853719134976">
<ol start="376" class="pre-context" id="pre133853719134976">
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> exc.raw_data,</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> status_code=exc.status_code,</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> headers=exc.headers,</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> cookies=getattr(exc, 'cookies', None),</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> renderer=getattr(exc, 'renderer', None),</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> )</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> except Exception as exc:</pre></li>
</ol>
<ol start="383" class="context-line">
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> func_result = self.handle_error(controller, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='384' class="post-context" id="post133853719134976">
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> return self._make_http_response(controller, func_result)</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre></pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> return decorator</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre></pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> def _run_checks(self, controller: 'Controller[BaseSerializer]') -> None:</pre></li>
<li onclick="toggle('pre133853719134976', 'post133853719134976')"><pre> # Run sync auth checks:</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719134976">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>context</td>
<td class="code"><pre>{'parsed_body': TwoNumbers(left=1, right=0)}</pre></td>
</tr>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
<tr>
<td>func</td>
<td class="code"><pre><function post at 0x79bd3f70c180></pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 222, in handle_error
<div class="context" id="c133853719134848">
<ol start="215" class="pre-context" id="pre133853719134848">
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> return controller.handle_error(</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> controller,</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> exc,</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> )</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> except Exception:</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> # And the last option is to handle error globally:</pre></li>
</ol>
<ol start="222" class="context-line">
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> return self._global_error_handler(controller, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='223' class="post-context" id="post133853719134848">
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre></pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> async def handle_async_error(</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> controller: 'Controller[BaseSerializer]',</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> exc: Exception,</pre></li>
<li onclick="toggle('pre133853719134848', 'post133853719134848')"><pre> ) -> HttpResponse:</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719134848">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>ZeroDivisionError('division by zero')</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 482, in _global_error_handler
<div class="context" id="c133853719134528">
<ol start="475" class="pre-context" id="pre133853719134528">
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> exc: Exception,</pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> ) -> HttpResponse:</pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> """</pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> Import the global error handling and call it.</pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre></pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> If not class level error handling has happened.</pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> """</pre></li>
</ol>
<ol start="482" class="context-line">
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> return resolve_setting( # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='483' class="post-context" id="post133853719134528">
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> Settings.global_error_handler,</pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> import_string=True,</pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre> )(self, controller, exc)</pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre></pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre></pre></li>
<li onclick="toggle('pre133853719134528', 'post133853719134528')"><pre>_ParamT = ParamSpec('_ParamT')</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719134528">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>ZeroDivisionError('division by zero')</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/errors.py</code>, line 314, in global_error_handler
<div class="context" id="c133853719134720">
<ol start="307" class="pre-context" id="pre133853719134720">
<li onclick="toggle('pre133853719134720', 'post133853719134720')"><pre> return controller.to_error(</pre></li>
<li onclick="toggle('pre133853719134720', 'post133853719134720')"><pre> controller.format_error(exc),</pre></li>
<li onclick="toggle('pre133853719134720', 'post133853719134720')"><pre> status_code=exc.status_code,</pre></li>
<li onclick="toggle('pre133853719134720', 'post133853719134720')"><pre> headers=getattr(exc, 'headers', None),</pre></li>
<li onclick="toggle('pre133853719134720', 'post133853719134720')"><pre> cookies=getattr(exc, 'cookies', None),</pre></li>
<li onclick="toggle('pre133853719134720', 'post133853719134720')"><pre> renderer=getattr(exc, 'renderer', None),</pre></li>
<li onclick="toggle('pre133853719134720', 'post133853719134720')"><pre> )</pre></li>
</ol>
<ol start="314" class="context-line">
<li onclick="toggle('pre133853719134720', 'post133853719134720')"><pre> raise exc from None
^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719134720">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
<tr>
<td>endpoint</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>ZeroDivisionError('division by zero')</pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 215, in handle_error
<div class="context" id="c133853719116736">
<ol start="208" class="pre-context" id="pre133853719116736">
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> )</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> except Exception: # noqa: S110</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> # We don't use `suppress` here for speed.</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> pass # noqa: WPS420</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> # Per-endpoint error handler didn't work.</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> # Now, try the per-controller one.</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> try:</pre></li>
</ol>
<ol start="215" class="context-line">
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> return controller.handle_error(
</pre> <span>…</span></li>
</ol>
<ol start='216' class="post-context" id="post133853719116736">
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> controller,</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> exc,</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> )</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> except Exception:</pre></li>
<li onclick="toggle('pre133853719116736', 'post133853719116736')"><pre> # And the last option is to handle error globally:</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719116736">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>ZeroDivisionError('division by zero')</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/controller.py</code>, line 329, in handle_error
<div class="context" id="c133853719116608">
<ol start="322" class="pre-context" id="pre133853719116608">
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> """</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> Return error response if possible. Sync case.</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre></pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> Override this method to add custom error handling for sync execution.</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> By default - does nothing, only re-raises the passed error.</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> Won't be called when using async endpoints.</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> """</pre></li>
</ol>
<ol start="329" class="context-line">
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> raise exc from None
^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='330' class="post-context" id="post133853719116608">
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre></pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> async def handle_async_error(</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> endpoint: Endpoint,</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> controller: 'Controller[_SerializerT_co]',</pre></li>
<li onclick="toggle('pre133853719116608', 'post133853719116608')"><pre> exc: Exception,</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719116608">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
<tr>
<td>endpoint</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>ZeroDivisionError('division by zero')</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 373, in decorator
<div class="context" id="c133853719116992">
<ol start="366" class="pre-context" id="pre133853719116992">
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> # Run checks:</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> self._run_checks(controller)</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre></pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> # Parse request:</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> context = self._serializer_context(self, controller)</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre></pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> # Return response:</pre></li>
</ol>
<ol start="373" class="context-line">
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> func_result = func(controller, **context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='374' class="post-context" id="post133853719116992">
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> except (APIError, APIRedirectError) as exc:</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> func_result = controller.to_error(</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> exc.raw_data,</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> status_code=exc.status_code,</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> headers=exc.headers,</pre></li>
<li onclick="toggle('pre133853719116992', 'post133853719116992')"><pre> cookies=getattr(exc, 'cookies', None),</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719116992">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>context</td>
<td class="code"><pre>{'parsed_body': TwoNumbers(left=1, right=0)}</pre></td>
</tr>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
<tr>
<td>func</td>
<td class="code"><pre><function post at 0x79bd3f70c180></pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f79e2c0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/docs/examples/error_handling/endpoint.py</code>, line 45, in post
<div class="context" id="c133853719116288">
<ol start="38" class="pre-context" id="pre133853719116288">
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre> ) -> float: # <- has custom error handling</pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre> return parsed_body.left / parsed_body.right</pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre></pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre> def post(</pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre> parsed_body: Body[TwoNumbers],</pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre> ) -> float: # <- has only default error handling</pre></li>
</ol>
<ol start="45" class="context-line">
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre> return parsed_body.left / parsed_body.right
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='46' class="post-context" id="post133853719116288">
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre></pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre></pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre># run: {"controller": "MathController", "method": "patch", "body": {"left": 1, "right": 0}, "url": "/api/math/", "curl_args": ["-D", "-"], "assert-error-text": "division by zero", "fail-with-body": false} # noqa: ERA001, E501</pre></li>
<li onclick="toggle('pre133853719116288', 'post133853719116288')"><pre># run: {"controller": "MathController", "method": "post", "body": {"left": 1, "right": 0}, "url": "/api/math/", "curl_args": ["-D", "-"], "assert-error-text": "Internal server error", "fail-with-body": false} # noqa: ERA001, E501</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719116288">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>parsed_body</td>
<td class="code"><pre>TwoNumbers(left=1, right=0)</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><examples.error_handling.endpoint.MathController object at 0x79bd3fae6360></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
</ul>
</div>
<form action="https://dpaste.com/" name="pasteform" id="pasteform" method="post">
<div id="pastebinTraceback" class="pastebin">
<input type="hidden" name="language" value="PythonConsole">
<input type="hidden" name="title"
value="ZeroDivisionError at /api/math/">
<input type="hidden" name="source" value="Django Dpaste Agent">
<input type="hidden" name="poster" value="Django">
<textarea name="content" id="traceback_area" cols="140" rows="25">
Environment:
Request Method: POST
Request URL: http://127.0.0.1:52227/api/math/
Django Version: 5.2.13
Python Version: 3.12.10
Installed Applications:
['django.contrib.auth',
'django.contrib.sessions',
'django.contrib.contenttypes',
'dmr',
'dmr.security.jwt.blocklist',
'server.apps.model_simple',
'server.apps.model_fk']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/core/handlers/exception.py", line 42, in inner
response = await get_response(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/core/handlers/base.py", line 253, in _get_response_async
response = await wrapped_callback(
File "/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/concurrent/futures/thread.py", line 59, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper
return view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/views/generic/base.py", line 105, in view
return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/controller.py", line 224, in dispatch
return endpoint(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 183, in __call__
return self._func( # type: ignore[no-any-return]
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 383, in decorator
func_result = self.handle_error(controller, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 222, in handle_error
return self._global_error_handler(controller, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 482, in _global_error_handler
return resolve_setting( # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/errors.py", line 314, in global_error_handler
raise exc from None
^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 215, in handle_error
return controller.handle_error(
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/controller.py", line 329, in handle_error
raise exc from None
^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 373, in decorator
func_result = func(controller, **context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/docs/examples/error_handling/endpoint.py", line 45, in post
return parsed_body.left / parsed_body.right
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Exception Type: ZeroDivisionError at /api/math/
Exception Value: division by zero
</textarea>
<br><br>
<input type="submit" value="Share this traceback on a public website">
</div>
</form>
</div>
<div id="requestinfo">
<h2>Request information</h2>
<h3 id="user-info">USER</h3>
<p>AnonymousUser</p>
<h3 id="get-info">GET</h3>
<p>No GET data</p>
<h3 id="post-info">POST</h3>
<p>No POST data</p>
<h3 id="files-info">FILES</h3>
<p>No FILES data</p>
<h3 id="cookie-info">COOKIES</h3>
<p>No cookie data</p>
<h3 id="meta-info">META</h3>
<table class="req">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>CONTENT_LENGTH</td>
<td class="code"><pre>'23'</pre></td>
</tr>
<tr>
<td>CONTENT_TYPE</td>
<td class="code"><pre>'application/json'</pre></td>
</tr>
<tr>
<td>HTTP_ACCEPT</td>
<td class="code"><pre>'*/*'</pre></td>
</tr>
<tr>
<td>HTTP_HOST</td>
<td class="code"><pre>'127.0.0.1:52227'</pre></td>
</tr>
<tr>
<td>HTTP_USER_AGENT</td>
<td class="code"><pre>'curl/7.81.0'</pre></td>
</tr>
<tr>
<td>PATH_INFO</td>
<td class="code"><pre>'/api/math/'</pre></td>
</tr>
<tr>
<td>QUERY_STRING</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>REMOTE_ADDR</td>
<td class="code"><pre>'127.0.0.1'</pre></td>
</tr>
<tr>
<td>REMOTE_HOST</td>
<td class="code"><pre>'127.0.0.1'</pre></td>
</tr>
<tr>
<td>REMOTE_PORT</td>
<td class="code"><pre>57524</pre></td>
</tr>
<tr>
<td>REQUEST_METHOD</td>
<td class="code"><pre>'POST'</pre></td>
</tr>
<tr>
<td>SCRIPT_NAME</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>SERVER_NAME</td>
<td class="code"><pre>'127.0.0.1'</pre></td>
</tr>
<tr>
<td>SERVER_PORT</td>
<td class="code"><pre>'52227'</pre></td>
</tr>
<tr>
<td>wsgi.multiprocess</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>wsgi.multithread</td>
<td class="code"><pre>True</pre></td>
</tr>
</tbody>
</table>
<h3 id="settings-info">Settings</h3>
<h4>Using settings module <code></code></h4>
<table class="req">
<thead>
<tr>
<th scope="col">Setting</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>ABSOLUTE_URL_OVERRIDES</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>ADMINS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>ALLOWED_HOSTS</td>
<td class="code"><pre>['*']</pre></td>
</tr>
<tr>
<td>APPEND_SLASH</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>AUTHENTICATION_BACKENDS</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>AUTH_PASSWORD_VALIDATORS</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>AUTH_USER_MODEL</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>CACHES</td>
<td class="code"><pre>{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}</pre></td>
</tr>
<tr>
<td>CACHE_MIDDLEWARE_ALIAS</td>
<td class="code"><pre>'default'</pre></td>
</tr>
<tr>
<td>CACHE_MIDDLEWARE_KEY_PREFIX</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>CACHE_MIDDLEWARE_SECONDS</td>
<td class="code"><pre>600</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_AGE</td>
<td class="code"><pre>31449600</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_DOMAIN</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_HTTPONLY</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_NAME</td>
<td class="code"><pre>'csrftoken'</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_PATH</td>
<td class="code"><pre>'/'</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_SAMESITE</td>
<td class="code"><pre>'Lax'</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_SECURE</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>CSRF_FAILURE_VIEW</td>
<td class="code"><pre>'django.views.csrf.csrf_failure'</pre></td>
</tr>
<tr>
<td>CSRF_HEADER_NAME</td>
<td class="code"><pre>'HTTP_X_CSRFTOKEN'</pre></td>
</tr>
<tr>
<td>CSRF_TRUSTED_ORIGINS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>CSRF_USE_SESSIONS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>DATABASES</td>
<td class="code"><pre>{'default': {'ATOMIC_REQUESTS': False,
'AUTOCOMMIT': True,
'CONN_HEALTH_CHECKS': False,
'CONN_MAX_AGE': 0,
'ENGINE': 'django.db.backends.sqlite3',
'HOST': '',
'NAME': '_build/test.db',
'OPTIONS': {},
'PASSWORD': '********************',
'PORT': '',
'TEST': {'CHARSET': None,
'COLLATION': None,
'MIGRATE': True,
'MIRROR': None,
'NAME': None},
'TIME_ZONE': None,
'USER': ''}}</pre></td>
</tr>
<tr>
<td>DATABASE_ROUTERS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>DATA_UPLOAD_MAX_MEMORY_SIZE</td>
<td class="code"><pre>2621440</pre></td>
</tr>
<tr>
<td>DATA_UPLOAD_MAX_NUMBER_FIELDS</td>
<td class="code"><pre>1000</pre></td>
</tr>
<tr>
<td>DATA_UPLOAD_MAX_NUMBER_FILES</td>
<td class="code"><pre>100</pre></td>
</tr>
<tr>
<td>DATETIME_FORMAT</td>
<td class="code"><pre>'N j, Y, P'</pre></td>
</tr>
<tr>
<td>DATETIME_INPUT_FORMATS</td>
<td class="code"><pre>['%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M',
'%m/%d/%Y %H:%M:%S',
'%m/%d/%Y %H:%M:%S.%f',
'%m/%d/%Y %H:%M',
'%m/%d/%y %H:%M:%S',
'%m/%d/%y %H:%M:%S.%f',
'%m/%d/%y %H:%M']</pre></td>
</tr>
<tr>
<td>DATE_FORMAT</td>
<td class="code"><pre>'N j, Y'</pre></td>
</tr>
<tr>
<td>DATE_INPUT_FORMATS</td>
<td class="code"><pre>['%Y-%m-%d',
'%m/%d/%Y',
'%m/%d/%y',
'%b %d %Y',
'%b %d, %Y',
'%d %b %Y',
'%d %b, %Y',
'%B %d %Y',
'%B %d, %Y',
'%d %B %Y',
'%d %B, %Y']</pre></td>
</tr>
<tr>
<td>DEBUG</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>DEBUG_PROPAGATE_EXCEPTIONS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>DECIMAL_SEPARATOR</td>
<td class="code"><pre>'.'</pre></td>
</tr>
<tr>
<td>DEFAULT_AUTO_FIELD</td>
<td class="code"><pre>'django.db.models.BigAutoField'</pre></td>
</tr>
<tr>
<td>DEFAULT_CHARSET</td>
<td class="code"><pre>'utf-8'</pre></td>
</tr>
<tr>
<td>DEFAULT_EXCEPTION_REPORTER</td>
<td class="code"><pre>'django.views.debug.ExceptionReporter'</pre></td>
</tr>
<tr>
<td>DEFAULT_EXCEPTION_REPORTER_FILTER</td>
<td class="code"><pre>'django.views.debug.SafeExceptionReporterFilter'</pre></td>
</tr>
<tr>
<td>DEFAULT_FROM_EMAIL</td>
<td class="code"><pre>'webmaster@localhost'</pre></td>
</tr>
<tr>
<td>DEFAULT_INDEX_TABLESPACE</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>DEFAULT_TABLESPACE</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>DISALLOWED_USER_AGENTS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>EMAIL_BACKEND</td>
<td class="code"><pre>'django.core.mail.backends.smtp.EmailBackend'</pre></td>
</tr>
<tr>
<td>EMAIL_HOST</td>
<td class="code"><pre>'localhost'</pre></td>
</tr>
<tr>
<td>EMAIL_HOST_PASSWORD</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>EMAIL_HOST_USER</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>EMAIL_PORT</td>
<td class="code"><pre>25</pre></td>
</tr>
<tr>
<td>EMAIL_SSL_CERTFILE</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>EMAIL_SSL_KEYFILE</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>EMAIL_SUBJECT_PREFIX</td>
<td class="code"><pre>'[Django] '</pre></td>
</tr>
<tr>
<td>EMAIL_TIMEOUT</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>EMAIL_USE_LOCALTIME</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>EMAIL_USE_SSL</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>EMAIL_USE_TLS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_DIRECTORY_PERMISSIONS</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_HANDLERS</td>
<td class="code"><pre>['django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler']</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_MAX_MEMORY_SIZE</td>
<td class="code"><pre>2621440</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_PERMISSIONS</td>
<td class="code"><pre>420</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_TEMP_DIR</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>FIRST_DAY_OF_WEEK</td>
<td class="code"><pre>0</pre></td>
</tr>
<tr>
<td>FIXTURE_DIRS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>FORCE_SCRIPT_NAME</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>FORMAT_MODULE_PATH</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>FORMS_URLFIELD_ASSUME_HTTPS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>FORM_RENDERER</td>
<td class="code"><pre>'django.forms.renderers.DjangoTemplates'</pre></td>
</tr>
<tr>
<td>HTTP_BASIC_PASSWORD</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>HTTP_BASIC_USERNAME</td>
<td class="code"><pre>'admin'</pre></td>
</tr>
<tr>
<td>IGNORABLE_404_URLS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>INSTALLED_APPS</td>
<td class="code"><pre>['django.contrib.auth',
'django.contrib.sessions',
'django.contrib.contenttypes',
'dmr',
'dmr.security.jwt.blocklist',
'server.apps.model_simple',
'server.apps.model_fk']</pre></td>
</tr>
<tr>
<td>INTERNAL_IPS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>LANGUAGES</td>
<td class="code"><pre>(('en', 'English'), ('ru', 'Russian'))</pre></td>
</tr>
<tr>
<td>LANGUAGES_BIDI</td>
<td class="code"><pre>['he', 'ar', 'ar-dz', 'ckb', 'fa', 'ug', 'ur']</pre></td>
</tr>
<tr>
<td>LANGUAGE_CODE</td>
<td class="code"><pre>'en-us'</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_AGE</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_DOMAIN</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_HTTPONLY</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_NAME</td>
<td class="code"><pre>'django_language'</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_PATH</td>
<td class="code"><pre>'/'</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_SAMESITE</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_SECURE</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>LOCALE_PATHS</td>
<td class="code"><pre>['/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/locale']</pre></td>
</tr>
<tr>
<td>LOGGING</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>LOGGING_CONFIG</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>LOGIN_REDIRECT_URL</td>
<td class="code"><pre>'/accounts/profile/'</pre></td>
</tr>
<tr>
<td>LOGIN_URL</td>
<td class="code"><pre>'/accounts/login/'</pre></td>
</tr>
<tr>
<td>LOGOUT_REDIRECT_URL</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>MANAGERS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>MEDIA_ROOT</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>MEDIA_URL</td>
<td class="code"><pre>'/'</pre></td>
</tr>
<tr>
<td>MESSAGE_STORAGE</td>
<td class="code"><pre>'django.contrib.messages.storage.fallback.FallbackStorage'</pre></td>
</tr>
<tr>
<td>MIDDLEWARE</td>
<td class="code"><pre>['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']</pre></td>
</tr>
<tr>
<td>MIGRATION_MODULES</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>MONTH_DAY_FORMAT</td>
<td class="code"><pre>'F j'</pre></td>
</tr>
<tr>
<td>NUMBER_GROUPING</td>
<td class="code"><pre>0</pre></td>
</tr>
<tr>
<td>PASSWORD_HASHERS</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>PASSWORD_RESET_TIMEOUT</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>PREPEND_WWW</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>ROOT_URLCONF</td>
<td class="code"><pre>'url_conf'</pre></td>
</tr>
<tr>
<td>SECRET_KEY</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>SECRET_KEY_FALLBACKS</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>SECURE_CONTENT_TYPE_NOSNIFF</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>SECURE_CROSS_ORIGIN_OPENER_POLICY</td>
<td class="code"><pre>'same-origin'</pre></td>
</tr>
<tr>
<td>SECURE_HSTS_INCLUDE_SUBDOMAINS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SECURE_HSTS_PRELOAD</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SECURE_HSTS_SECONDS</td>
<td class="code"><pre>0</pre></td>
</tr>
<tr>
<td>SECURE_PROXY_SSL_HEADER</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>SECURE_REDIRECT_EXEMPT</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>SECURE_REFERRER_POLICY</td>
<td class="code"><pre>'same-origin'</pre></td>
</tr>
<tr>
<td>SECURE_SSL_HOST</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>SECURE_SSL_REDIRECT</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SERVER_EMAIL</td>
<td class="code"><pre>'root@localhost'</pre></td>
</tr>
<tr>
<td>SESSION_CACHE_ALIAS</td>
<td class="code"><pre>'default'</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_AGE</td>
<td class="code"><pre>1209600</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_DOMAIN</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_HTTPONLY</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_NAME</td>
<td class="code"><pre>'sessionid'</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_PATH</td>
<td class="code"><pre>'/'</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_SAMESITE</td>
<td class="code"><pre>'Lax'</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_SECURE</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SESSION_ENGINE</td>
<td class="code"><pre>'django.contrib.sessions.backends.db'</pre></td>
</tr>
<tr>
<td>SESSION_EXPIRE_AT_BROWSER_CLOSE</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SESSION_FILE_PATH</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>SESSION_SAVE_EVERY_REQUEST</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SESSION_SERIALIZER</td>
<td class="code"><pre>'django.contrib.sessions.serializers.JSONSerializer'</pre></td>
</tr>
<tr>
<td>SHORT_DATETIME_FORMAT</td>
<td class="code"><pre>'m/d/Y P'</pre></td>
</tr>
<tr>
<td>SHORT_DATE_FORMAT</td>
<td class="code"><pre>'m/d/Y'</pre></td>
</tr>
<tr>
<td>SIGNING_BACKEND</td>
<td class="code"><pre>'django.core.signing.TimestampSigner'</pre></td>
</tr>
<tr>
<td>SILENCED_SYSTEM_CHECKS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>STATICFILES_DIRS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>STATICFILES_FINDERS</td>
<td class="code"><pre>['django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder']</pre></td>
</tr>
<tr>
<td>STATIC_ROOT</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>STATIC_URL</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>STORAGES</td>
<td class="code"><pre>{'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage'},
'staticfiles': {'BACKEND': 'django.contrib.staticfiles.storage.StaticFilesStorage'}}</pre></td>
</tr>
<tr>
<td>TEMPLATES</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>TEST_NON_SERIALIZED_APPS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>TEST_RUNNER</td>
<td class="code"><pre>'django.test.runner.DiscoverRunner'</pre></td>
</tr>
<tr>
<td>THOUSAND_SEPARATOR</td>
<td class="code"><pre>','</pre></td>
</tr>
<tr>
<td>TIME_FORMAT</td>
<td class="code"><pre>'P'</pre></td>
</tr>
<tr>
<td>TIME_INPUT_FORMATS</td>
<td class="code"><pre>['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']</pre></td>
</tr>
<tr>
<td>TIME_ZONE</td>
<td class="code"><pre>'America/Chicago'</pre></td>
</tr>
<tr>
<td>USE_I18N</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>USE_THOUSAND_SEPARATOR</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>USE_TZ</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>USE_X_FORWARDED_HOST</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>USE_X_FORWARDED_PORT</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>WSGI_APPLICATION</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>X_FRAME_OPTIONS</td>
<td class="code"><pre>'DENY'</pre></td>
</tr>
<tr>
<td>YEAR_MONTH_FORMAT</td>
<td class="code"><pre>'F Y'</pre></td>
</tr>
</tbody>
</table>
</div>
</main>
<footer id="explanation">
<p>
You’re seeing this error because you have <code>DEBUG = True</code> in your
Django settings file. Change that to <code>False</code>, and Django will
display a standard page generated by the handler for this status code.
</p>
</footer>
</body>
</html>
In this example we add error handling defined as division_error
to patch endpoint (which serves as a division operation),
while keeping post endpoint (which serves as a multiply operation)
without a custom error handler.
Because ZeroDivisionError can’t happen in post.
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:
1from http import HTTPStatus
2
3import pydantic
4from django.http import HttpResponse
5
6from dmr import Body, Controller, modify
7from dmr.endpoint import Endpoint
8from dmr.errors import wrap_handler
9from dmr.plugins.pydantic import PydanticSerializer
10from dmr.serializer import BaseSerializer
11
12
13class TwoNumbers(pydantic.BaseModel):
14 left: int
15 right: int
16
17
18class MathController(Controller[PydanticSerializer]):
19 def division_error( # <- we define an error handler
20 self,
21 endpoint: Endpoint,
22 controller: Controller[BaseSerializer],
23 exc: Exception,
24 ) -> HttpResponse:
25 if isinstance(exc, ZeroDivisionError):
26 # This response's schema was automatically added by `Body`:
27 return controller.to_error(
28 controller.format_error(str(exc)),
29 status_code=HTTPStatus.BAD_REQUEST,
30 )
31 # Reraise unfamiliar errors to let someone
32 # else to handle them further.
33 raise exc from None
34
35 @modify(
36 error_handler=wrap_handler( # <- and we pass the handler
37 division_error,
38 ),
39 )
40 def patch(
41 self,
42 parsed_body: Body[TwoNumbers],
43 ) -> float: # <- has custom error handling
44 return parsed_body.left / parsed_body.right
45
46 def post(
47 self,
48 parsed_body: Body[TwoNumbers],
49 ) -> float: # <- has only default error handling
50 return parsed_body.left * parsed_body.right
51
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: Thu, 09 Apr 2026 14:41:27 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:
1from http import HTTPStatus
2
3import zapros
4from django.http import HttpResponse
5from typing_extensions import override
6
7from dmr import Controller, ResponseSpec
8from dmr.endpoint import Endpoint
9from dmr.plugins.pydantic import PydanticSerializer
10
11
12class ProxyController(Controller[PydanticSerializer]):
13 responses = (
14 # Custom schema that we can return when `HTTPError` happens:
15 ResponseSpec(str, status_code=HTTPStatus.FAILED_DEPENDENCY),
16 )
17
18 async def get(self) -> None:
19 async with self._client() as client:
20 # Simulate some real work:
21 await client.get('https://example.com')
22
23 async def post(self) -> None:
24 async with self._client() as client:
25 # Simulate some real work:
26 await client.post('https://example.com', json={})
27
28 @override
29 async def handle_async_error(
30 self,
31 endpoint: Endpoint,
32 controller: Controller[PydanticSerializer],
33 exc: Exception,
34 ) -> HttpResponse:
35 # Will handle errors in all endpoints.
36 if isinstance(exc, zapros.ZaprosError):
37 return self.to_error(
38 'Request to example.com failed',
39 status_code=HTTPStatus.FAILED_DEPENDENCY,
40 )
41 # Handle errors from super:
42 return await super().handle_async_error(
43 endpoint,
44 controller,
45 exc,
46 )
47
48 def _client(self) -> zapros.AsyncClient:
49 return zapros.AsyncClient()
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
ResponseSpecobjects for new error response schemas
You can dive even deeper and:
Subclass
Controllerand provide default error handling for this specific subclassRedefine
endpoint_clsand change how one specific endpoint behaves on a deep level, seehandle_error()andhandle_async_error()
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.
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:
error_modelattribute for all controllers that will be using this error message schemaformat_error()method to provide custom runtime error formatting
1from http import HTTPStatus
2
3from typing_extensions import TypedDict, override
4
5from dmr import APIError, Body, Controller, ResponseSpec, modify
6from dmr.errors import ErrorType, format_error
7from dmr.plugins.pydantic import PydanticSerializer
8
9
10class CustomErrorDetail(TypedDict):
11 message: str
12
13
14class CustomErrorModel(TypedDict):
15 errors: list[CustomErrorDetail]
16
17
18class ApiController(Controller[PydanticSerializer]):
19 error_model = CustomErrorModel
20
21 @override
22 def format_error(
23 self,
24 error: str | Exception,
25 *,
26 loc: str | list[str | int] | None = None,
27 error_type: str | ErrorType | None = None,
28 ) -> CustomErrorModel:
29 default = format_error(
30 error,
31 loc=loc,
32 error_type=error_type,
33 )
34 return {
35 'errors': [
36 {'message': detail['msg']} for detail in default['detail']
37 ],
38 }
39
40 @modify(
41 extra_responses=[
42 ResponseSpec(
43 return_type=CustomErrorModel,
44 status_code=HTTPStatus.PAYMENT_REQUIRED,
45 ),
46 ],
47 )
48 def post(self, parsed_body: Body[dict[str, str]]) -> str:
49 raise APIError(
50 self.format_error('test msg'),
51 status_code=HTTPStatus.PAYMENT_REQUIRED,
52 )
53
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"
}
},
"securitySchemes": {}
},
"info": {
"title": "Django Modern Rest",
"version": "0.1.0"
},
"openapi": "3.2.0",
"paths": {
"/api/apicontroller/": {
"post": {
"deprecated": false,
"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.
Problem Details¶
See also
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:
Define
error_modelattribute asProblemDetailsModelRaise an exception itself, pass all the required fields
Convert other message to the Problem Details format using
format_error()method
1from http import HTTPStatus
2from typing import Any
3
4import pydantic
5from typing_extensions import override
6
7from dmr import Controller, Query, ResponseSpec
8from dmr.errors import ErrorType
9from dmr.plugins.pydantic import PydanticSerializer
10from dmr.problem_details import ProblemDetailsError, ProblemDetailsModel
11
12
13class _QueryModel(pydantic.BaseModel):
14 number: int = 0
15
16
17class ProblemDetailsController(Controller[PydanticSerializer]):
18 error_model = ProblemDetailsModel
19
20 responses = (
21 ResponseSpec(error_model, status_code=HTTPStatus.PAYMENT_REQUIRED),
22 )
23
24 async def get(self, parsed_query: Query[_QueryModel]) -> str:
25 raise ProblemDetailsError(
26 (
27 f'Your current balance is {parsed_query.number}, '
28 'but the price is 15'
29 ),
30 status_code=HTTPStatus.PAYMENT_REQUIRED,
31 type='https://example.com/probs/out-of-credit',
32 title='Not enough funds',
33 instance='/account/users/1/',
34 extra={'balance': parsed_query.number, 'price': 15},
35 )
36
37 @override
38 def format_error(
39 self,
40 error: str | Exception,
41 *,
42 loc: str | list[str | int] | None = None,
43 error_type: str | ErrorType | None = None,
44 ) -> Any:
45 return ProblemDetailsError.format_error(
46 error,
47 loc=loc,
48 error_type=error_type,
49 title='From format_error',
50 )
51
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"
}
},
"securitySchemes": {}
},
"info": {
"title": "Django Modern Rest",
"version": "0.1.0"
},
"openapi": "3.2.0",
"paths": {
"/api/problemdetailscontroller/": {
"get": {
"deprecated": false,
"operationId": "getProblemdetailscontrollerApiProblemdetailscontroller",
"parameters": [
{
"deprecated": false,
"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?
When user sends a request with
Acceptheader withapplication/problem+jsoncontent type, we will return Problem Details errorsWhen
application/jsonor any other content type is sent, we return regularErrorModelerror payloads
To do so, you would need a slightly more difficult setup:
Define
error_modelattribute as the result oferror_model()method call. It will add conditional schema types to your error responsesDefine several
Renderertypes, including the one which will handleapplication/problem+jsonRaise a conditional exception: use
conditional_error()to only raise Problem Details when the correct accepted type is passedConvert other message to the Problem Details format using
format_error()method when the correct accepted type is passed
1from http import HTTPStatus
2from typing import Any
3
4from typing_extensions import override
5
6from dmr import Controller, ResponseSpec
7from dmr.errors import ErrorModel, ErrorType
8from dmr.negotiation import ContentType, accepts
9from dmr.plugins.pydantic import PydanticSerializer
10from dmr.problem_details import ProblemDetailsError
11from dmr.renderers import JsonRenderer
12
13
14class ProblemDetailsController(Controller[PydanticSerializer]):
15 error_model = ProblemDetailsError.error_model({
16 ContentType.json: ErrorModel,
17 })
18
19 renderers = (
20 JsonRenderer(ContentType.json),
21 JsonRenderer(ContentType.json_problem_details),
22 )
23
24 responses = (
25 ResponseSpec(error_model, status_code=HTTPStatus.PAYMENT_REQUIRED),
26 )
27
28 async def get(self) -> str:
29 raise ProblemDetailsError.conditional_error(
30 'Your current balance is 0, but the price is 15',
31 status_code=HTTPStatus.PAYMENT_REQUIRED,
32 type='https://example.com/probs/out-of-credit',
33 title='Not enough funds',
34 instance='/account/users/1/',
35 extra={'balance': 0, 'price': 15},
36 controller=self,
37 )
38
39 @override
40 def format_error(
41 self,
42 error: str | Exception,
43 *,
44 loc: str | list[str | int] | None = None,
45 error_type: str | ErrorType | None = None,
46 ) -> Any:
47 if accepts(self.request, ContentType.json_problem_details):
48 return ProblemDetailsError.format_error(
49 error,
50 loc=loc,
51 error_type=error_type,
52 title='From format_error',
53 )
54 return super().format_error(error, loc=loc, error_type=error_type)
55
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"
}
},
"securitySchemes": {}
},
"info": {
"title": "Django Modern Rest",
"version": "0.1.0"
},
"openapi": "3.2.0",
"paths": {
"/api/problemdetailscontroller/": {
"get": {
"deprecated": false,
"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:
1from typing import Literal
2
3import pydantic
4
5from dmr import Controller
6from dmr.plugins.pydantic import PydanticSerializer
7
8
9class Pong(pydantic.BaseModel):
10 message: Literal['pong']
11
12
13class PongController(Controller[PydanticSerializer]):
14 def get(self) -> Pong:
15 # This will trigger `pydantic.ValidationError`,
16 # because `message` must be `'pong'`, not `'wrong'`:
17 return Pong(message='wrong')
18
Run result
$ curl http://127.0.0.1:8000/api/ping/ -D - -X GET
HTTP/1.1 500 Internal Server Error
date: Thu, 09 Apr 2026 14:41:30 GMT
server: uvicorn
Content-Type: text/html; charset=utf-8
X-Frame-Options: DENY
Vary: Accept-Language, Cookie
Content-Language: en
Content-Length: 105360
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE">
<title>ValidationError
at /api/ping/</title>
<style>
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font-family: sans-serif; background-color:#fff; color:#000; }
body > :where(header, main, footer) { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; }
h2 { margin-bottom:.8em; }
h3 { margin:1em 0 .5em 0; }
h4 { margin:0 0 .5em 0; font-weight: normal; }
code, pre { font-size: 100%; white-space: pre-wrap; word-break: break-word; }
summary { cursor: pointer; }
table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
tbody td, tbody th { vertical-align:top; padding:2px 3px; }
thead th {
padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
font-weight:normal; font-size: 0.6875rem; border:1px solid #ddd;
}
tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
table.vars { margin:5px 10px 2px 40px; width: auto; }
table.vars td, table.req td { font-family:monospace; }
table td.code { width:100%; }
table td.code pre { overflow:hidden; }
table.source th { color:#666; }
table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
ul.traceback { list-style-type:none; color: #222; }
ul.traceback li.cause { word-break: break-word; }
ul.traceback li.frame { padding-bottom:1em; color:#4f4f4f; }
ul.traceback li.user { background-color:#e0e0e0; color:#000 }
div.context { padding:10px 0; overflow:hidden; }
div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; }
div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; padding-left: 2px; }
div.context ol li pre { display:inline; }
div.context ol.context-line li { color:#464646; background-color:#dfdfdf; padding: 3px 2px; }
div.context ol.context-line li span { position:absolute; right:32px; }
.user div.context ol.context-line li { background-color:#bbb; color:#000; }
.user div.context ol li { color:#666; }
div.commands, summary.commands { margin-left: 40px; }
div.commands a, summary.commands { color:#555; text-decoration:none; }
.user div.commands a { color: black; }
#summary { background: #ffc; }
#summary h2 { font-weight: normal; color: #666; }
#info { padding: 0; }
#info > * { padding:10px 20px; }
#explanation { background:#eee; }
#template, #template-not-exist { background:#f6f6f6; }
#template-not-exist ul { margin: 0 0 10px 20px; }
#template-not-exist .postmortem-section { margin-bottom: 3px; }
#unicode-hint { background:#eee; }
#traceback { background:#eee; }
#requestinfo { background:#f6f6f6; padding-left:120px; }
#summary table { border:none; background:transparent; }
#requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
#requestinfo h3 { margin-bottom:-1em; }
.error { background: #ffc; }
.specific { color:#cc3300; font-weight:bold; }
h2 span.commands { font-size: 0.7rem; font-weight:normal; }
span.commands a:link {color:#5E5694;}
pre.exception_value { font-family: sans-serif; color: #575757; font-size: 1.5rem; margin: 10px 0 10px 0; }
.append-bottom { margin-bottom: 10px; }
.fname { user-select: all; }
</style>
<script>
function hideAll(elems) {
for (var e = 0; e < elems.length; e++) {
elems[e].style.display = 'none';
}
}
window.onload = function() {
hideAll(document.querySelectorAll('ol.pre-context'));
hideAll(document.querySelectorAll('ol.post-context'));
hideAll(document.querySelectorAll('div.pastebin'));
}
function toggle() {
for (var i = 0; i < arguments.length; i++) {
var e = document.getElementById(arguments[i]);
if (e) {
e.style.display = e.style.display == 'none' ? 'block': 'none';
}
}
return false;
}
function switchPastebinFriendly(link) {
s1 = "Switch to copy-and-paste view";
s2 = "Switch back to interactive view";
link.textContent = link.textContent.trim() == s1 ? s2: s1;
toggle('browserTraceback', 'pastebinTraceback');
return false;
}
</script>
</head>
<body>
<header id="summary">
<h1>ValidationError
at /api/ping/</h1>
<pre class="exception_value">1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error</pre>
<table class="meta">
<tr>
<th scope="row">Request Method:</th>
<td>GET</td>
</tr>
<tr>
<th scope="row">Request URL:</th>
<td>http://127.0.0.1:56867/api/ping/</td>
</tr>
<tr>
<th scope="row">Django Version:</th>
<td>5.2.13</td>
</tr>
<tr>
<th scope="row">Exception Type:</th>
<td>ValidationError</td>
</tr>
<tr>
<th scope="row">Exception Value:</th>
<td><pre>1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error</pre></td>
</tr>
<tr>
<th scope="row">Exception Location:</th>
<td><span class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/pydantic/main.py</span>, line 250, in __init__</td>
</tr>
<tr>
<th scope="row">Raised during:</th>
<td>examples.error_handling.pydantic_validation_error.PongController</td>
</tr>
<tr>
<th scope="row">Python Executable:</th>
<td>/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/bin/python</td>
</tr>
<tr>
<th scope="row">Python Version:</th>
<td>3.12.10</td>
</tr>
<tr>
<th scope="row">Python Path:</th>
<td><pre><code>['/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0',
'/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/django_test_app',
'/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/docs',
'/home/docs/.asdf/installs/python/3.12.10/lib/python312.zip',
'/home/docs/.asdf/installs/python/3.12.10/lib/python3.12',
'/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/lib-dynload',
'/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages']</code></pre></td>
</tr>
<tr>
<th scope="row">Server time:</th>
<td>Thu, 09 Apr 2026 09:41:30 -0500</td>
</tr>
</table>
</header>
<main id="info">
<div id="traceback">
<h2>Traceback <span class="commands"><a href="#" role="button" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>
</h2>
<div id="browserTraceback">
<ul class="traceback">
<li class="frame django">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/core/handlers/exception.py</code>, line 42, in inner
<div class="context" id="c133853721403328">
<ol start="35" class="pre-context" id="pre133853721403328">
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> can rely on getting a response instead of an exception.</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> """</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> if iscoroutinefunction(get_response):</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre></pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> @wraps(get_response)</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> async def inner(request):</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> try:</pre></li>
</ol>
<ol start="42" class="context-line">
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> response = await get_response(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='43' class="post-context" id="post133853721403328">
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> except Exception as exc:</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> response = await sync_to_async(</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> response_for_exception, thread_sensitive=False</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> )(request, exc)</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre> return response</pre></li>
<li onclick="toggle('pre133853721403328', 'post133853721403328')"><pre></pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853721403328">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>exc</td>
<td class="code"><pre>1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error</pre></td>
</tr>
<tr>
<td>get_response</td>
<td class="code"><pre><bound method BaseHandler._get_response_async of <django.core.handlers.asgi.ASGIHandler object at 0x79bd3f92c4d0>></pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: GET '/api/ping/'></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame django">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/core/handlers/base.py</code>, line 253, in _get_response_async
<div class="context" id="c133853719342208">
<ol start="246" class="pre-context" id="pre133853719342208">
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> wrapped_callback = self.make_view_atomic(callback)</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> # If it is a synchronous view, run it in a subthread</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> if not iscoroutinefunction(wrapped_callback):</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> wrapped_callback = sync_to_async(</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> wrapped_callback, thread_sensitive=True</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> )</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> try:</pre></li>
</ol>
<ol start="253" class="context-line">
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> response = await wrapped_callback(
</pre> <span>…</span></li>
</ol>
<ol start='254' class="post-context" id="post133853719342208">
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> request, *callback_args, **callback_kwargs</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> )</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> except Exception as e:</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> response = await sync_to_async(</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> self.process_exception_by_middleware,</pre></li>
<li onclick="toggle('pre133853719342208', 'post133853719342208')"><pre> thread_sensitive=True,</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719342208">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>callback</td>
<td class="code"><pre><function View.as_view.<locals>.view at 0x79bd3f70eb60></pre></td>
</tr>
<tr>
<td>callback_args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>callback_kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>middleware_method</td>
<td class="code"><pre><asgiref.sync.SyncToAsync object at 0x79bd3f92ce60></pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: GET '/api/ping/'></pre></td>
</tr>
<tr>
<td>response</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><django.core.handlers.asgi.ASGIHandler object at 0x79bd3f92c4d0></pre></td>
</tr>
<tr>
<td>wrapped_callback</td>
<td class="code"><pre><asgiref.sync.SyncToAsync object at 0x79bd3fad53d0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/concurrent/futures/thread.py</code>, line 59, in run
<div class="context" id="c133853719341952">
<ol start="52" class="pre-context" id="pre133853719341952">
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> self.kwargs = kwargs</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre></pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> def run(self):</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> if not self.future.set_running_or_notify_cancel():</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> return</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre></pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> try:</pre></li>
</ol>
<ol start="59" class="context-line">
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='60' class="post-context" id="post133853719341952">
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> except BaseException as exc:</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> self.future.set_exception(exc)</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> # Break a reference cycle with the exception 'exc'</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> self = None</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> else:</pre></li>
<li onclick="toggle('pre133853719341952', 'post133853719341952')"><pre> self.future.set_result(result)</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719341952">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>self</td>
<td class="code"><pre>None</pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame django">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/views/decorators/csrf.py</code>, line 65, in _view_wrapper
<div class="context" id="c133853719340544">
<ol start="58" class="pre-context" id="pre133853719340544">
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre></pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre> async def _view_wrapper(request, *args, **kwargs):</pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre> return await view_func(request, *args, **kwargs)</pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre></pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre> else:</pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre></pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre> def _view_wrapper(request, *args, **kwargs):</pre></li>
</ol>
<ol start="65" class="context-line">
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre> return view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='66' class="post-context" id="post133853719340544">
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre></pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre> _view_wrapper.csrf_exempt = True</pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre></pre></li>
<li onclick="toggle('pre133853719340544', 'post133853719340544')"><pre> return wraps(view_func)(_view_wrapper)</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719340544">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: GET '/api/ping/'></pre></td>
</tr>
<tr>
<td>view_func</td>
<td class="code"><pre><function View.as_view.<locals>.view at 0x79bd3f70eac0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame django">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/views/generic/base.py</code>, line 105, in view
<div class="context" id="c133854000104384">
<ol start="98" class="pre-context" id="pre133854000104384">
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> self = cls(**initkwargs)</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> self.setup(request, *args, **kwargs)</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> if not hasattr(self, "request"):</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> raise AttributeError(</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> "%s instance has no 'request' attribute. Did you override "</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> "setup() and forget to call super()?" % cls.__name__</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> )</pre></li>
</ol>
<ol start="105" class="context-line">
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='106' class="post-context" id="post133854000104384">
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre></pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> view.view_class = cls</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> view.view_initkwargs = initkwargs</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre></pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> # __name__ and __qualname__ are intentionally left unchanged as</pre></li>
<li onclick="toggle('pre133854000104384', 'post133854000104384')"><pre> # view_class should be used to robustly determine the name of the view</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133854000104384">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>cls</td>
<td class="code"><pre><class 'examples.error_handling.pydantic_validation_error.PongController'></pre></td>
</tr>
<tr>
<td>initkwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: GET '/api/ping/'></pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/controller.py</code>, line 224, in dispatch
<div class="context" id="c133853719342144">
<ol start="217" class="pre-context" id="pre133853719342144">
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre></pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> Return 405 if this method is not allowed.</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> """</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> # Fast path for method resolution:</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> method: str = request.method # type: ignore[assignment]</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> endpoint = self.api_endpoints.get(method)</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> if endpoint is not None:</pre></li>
</ol>
<ol start="224" class="context-line">
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> return endpoint(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='225' class="post-context" id="post133853719342144">
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> # This return is very special,</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> # since it does not have an attached endpoint.</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> # All other responses are handled on endpoint level</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> # with all the response type validation.</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre> return self.handle_method_not_allowed(method)</pre></li>
<li onclick="toggle('pre133853719342144', 'post133853719342144')"><pre></pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719342144">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>endpoint</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>method</td>
<td class="code"><pre>'GET'</pre></td>
</tr>
<tr>
<td>request</td>
<td class="code"><pre><ASGIRequest: GET '/api/ping/'></pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 183, in __call__
<div class="context" id="c133853719346304">
<ol start="176" class="pre-context" id="pre133853719346304">
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> def __call__(</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> controller: 'Controller[BaseSerializer]',</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> *args: Any,</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> **kwargs: Any,</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> ) -> HttpResponseBase:</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> """Run the endpoint and return the response."""</pre></li>
</ol>
<ol start="183" class="context-line">
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> return self._func( # type: ignore[no-any-return]
</pre> <span>…</span></li>
</ol>
<ol start='184' class="post-context" id="post133853719346304">
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> controller,</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> *args,</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> **kwargs,</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> )</pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre></pre></li>
<li onclick="toggle('pre133853719346304', 'post133853719346304')"><pre> def handle_error(</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719346304">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 383, in decorator
<div class="context" id="c133853719342272">
<ol start="376" class="pre-context" id="pre133853719342272">
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> exc.raw_data,</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> status_code=exc.status_code,</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> headers=exc.headers,</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> cookies=getattr(exc, 'cookies', None),</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> renderer=getattr(exc, 'renderer', None),</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> )</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> except Exception as exc:</pre></li>
</ol>
<ol start="383" class="context-line">
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> func_result = self.handle_error(controller, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='384' class="post-context" id="post133853719342272">
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> return self._make_http_response(controller, func_result)</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre></pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> return decorator</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre></pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> def _run_checks(self, controller: 'Controller[BaseSerializer]') -> None:</pre></li>
<li onclick="toggle('pre133853719342272', 'post133853719342272')"><pre> # Run sync auth checks:</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719342272">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>context</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
<tr>
<td>func</td>
<td class="code"><pre><function get at 0x79bd3f70dda0></pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 222, in handle_error
<div class="context" id="c133853719346176">
<ol start="215" class="pre-context" id="pre133853719346176">
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> return controller.handle_error(</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> controller,</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> exc,</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> )</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> except Exception:</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> # And the last option is to handle error globally:</pre></li>
</ol>
<ol start="222" class="context-line">
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> return self._global_error_handler(controller, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='223' class="post-context" id="post133853719346176">
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre></pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> async def handle_async_error(</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> controller: 'Controller[BaseSerializer]',</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> exc: Exception,</pre></li>
<li onclick="toggle('pre133853719346176', 'post133853719346176')"><pre> ) -> HttpResponse:</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719346176">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 482, in _global_error_handler
<div class="context" id="c133853719340864">
<ol start="475" class="pre-context" id="pre133853719340864">
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> exc: Exception,</pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> ) -> HttpResponse:</pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> """</pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> Import the global error handling and call it.</pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre></pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> If not class level error handling has happened.</pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> """</pre></li>
</ol>
<ol start="482" class="context-line">
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> return resolve_setting( # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='483' class="post-context" id="post133853719340864">
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> Settings.global_error_handler,</pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> import_string=True,</pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre> )(self, controller, exc)</pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre></pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre></pre></li>
<li onclick="toggle('pre133853719340864', 'post133853719340864')"><pre>_ParamT = ParamSpec('_ParamT')</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719340864">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/errors.py</code>, line 314, in global_error_handler
<div class="context" id="c133853719343424">
<ol start="307" class="pre-context" id="pre133853719343424">
<li onclick="toggle('pre133853719343424', 'post133853719343424')"><pre> return controller.to_error(</pre></li>
<li onclick="toggle('pre133853719343424', 'post133853719343424')"><pre> controller.format_error(exc),</pre></li>
<li onclick="toggle('pre133853719343424', 'post133853719343424')"><pre> status_code=exc.status_code,</pre></li>
<li onclick="toggle('pre133853719343424', 'post133853719343424')"><pre> headers=getattr(exc, 'headers', None),</pre></li>
<li onclick="toggle('pre133853719343424', 'post133853719343424')"><pre> cookies=getattr(exc, 'cookies', None),</pre></li>
<li onclick="toggle('pre133853719343424', 'post133853719343424')"><pre> renderer=getattr(exc, 'renderer', None),</pre></li>
<li onclick="toggle('pre133853719343424', 'post133853719343424')"><pre> )</pre></li>
</ol>
<ol start="314" class="context-line">
<li onclick="toggle('pre133853719343424', 'post133853719343424')"><pre> raise exc from None
^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719343424">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
<tr>
<td>endpoint</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error</pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 215, in handle_error
<div class="context" id="c133853719345024">
<ol start="208" class="pre-context" id="pre133853719345024">
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> )</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> except Exception: # noqa: S110</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> # We don't use `suppress` here for speed.</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> pass # noqa: WPS420</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> # Per-endpoint error handler didn't work.</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> # Now, try the per-controller one.</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> try:</pre></li>
</ol>
<ol start="215" class="context-line">
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> return controller.handle_error(
</pre> <span>…</span></li>
</ol>
<ol start='216' class="post-context" id="post133853719345024">
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> controller,</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> exc,</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> )</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> except Exception:</pre></li>
<li onclick="toggle('pre133853719345024', 'post133853719345024')"><pre> # And the last option is to handle error globally:</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719345024">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/controller.py</code>, line 329, in handle_error
<div class="context" id="c133853719345216">
<ol start="322" class="pre-context" id="pre133853719345216">
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> """</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> Return error response if possible. Sync case.</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre></pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> Override this method to add custom error handling for sync execution.</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> By default - does nothing, only re-raises the passed error.</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> Won't be called when using async endpoints.</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> """</pre></li>
</ol>
<ol start="329" class="context-line">
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> raise exc from None
^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='330' class="post-context" id="post133853719345216">
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre></pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> async def handle_async_error(</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> self,</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> endpoint: Endpoint,</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> controller: 'Controller[_SerializerT_co]',</pre></li>
<li onclick="toggle('pre133853719345216', 'post133853719345216')"><pre> exc: Exception,</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853719345216">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
<tr>
<td>endpoint</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
<tr>
<td>exc</td>
<td class="code"><pre>1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py</code>, line 373, in decorator
<div class="context" id="c133854000805376">
<ol start="366" class="pre-context" id="pre133854000805376">
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> # Run checks:</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> self._run_checks(controller)</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre></pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> # Parse request:</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> context = self._serializer_context(self, controller)</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre></pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> # Return response:</pre></li>
</ol>
<ol start="373" class="context-line">
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> func_result = func(controller, **context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='374' class="post-context" id="post133854000805376">
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> except (APIError, APIRedirectError) as exc:</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> func_result = controller.to_error(</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> exc.raw_data,</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> status_code=exc.status_code,</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> headers=exc.headers,</pre></li>
<li onclick="toggle('pre133854000805376', 'post133854000805376')"><pre> cookies=getattr(exc, 'cookies', None),</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133854000805376">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>args</td>
<td class="code"><pre>()</pre></td>
</tr>
<tr>
<td>context</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>controller</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
<tr>
<td>func</td>
<td class="code"><pre><function get at 0x79bd3f70dda0></pre></td>
</tr>
<tr>
<td>kwargs</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre><dmr.endpoint.Endpoint object at 0x79bd3f87d8a0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/docs/examples/error_handling/pydantic_validation_error.py</code>, line 17, in get
<div class="context" id="c133854000300352">
<ol start="10" class="pre-context" id="pre133854000300352">
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre> message: Literal['pong']</pre></li>
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre></pre></li>
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre></pre></li>
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre>class PongController(Controller[PydanticSerializer]):</pre></li>
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre> def get(self) -> Pong:</pre></li>
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre> # This will trigger `pydantic.ValidationError`,</pre></li>
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre> # because `message` must be `'pong'`, not `'wrong'`:</pre></li>
</ol>
<ol start="17" class="context-line">
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre> return Pong(message='wrong')
^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='18' class="post-context" id="post133854000300352">
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre></pre></li>
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre></pre></li>
<li onclick="toggle('pre133854000300352', 'post133854000300352')"><pre># run: {"controller": "PongController", "method": "get", "url": "/api/ping/", "curl_args": ["-D", "-"], "assert-error-text": "Internal server error", "fail-with-body": false} # noqa: ERA001, E501</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133854000300352">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>self</td>
<td class="code"><pre><examples.error_handling.pydantic_validation_error.PongController object at 0x79bd3fad45f0></pre></td>
</tr>
</tbody>
</table>
</details>
</li>
<li class="frame user">
<code class="fname">/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/pydantic/main.py</code>, line 250, in __init__
<div class="context" id="c133853727867648">
<ol start="243" class="pre-context" id="pre133853727867648">
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> validated to form a valid model.</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre></pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> `self` is explicitly positional-only to allow `self` as a field name.</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> """</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> __tracebackhide__ = True</pre></li>
</ol>
<ol start="250" class="context-line">
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre> <span>…</span></li>
</ol>
<ol start='251' class="post-context" id="post133853727867648">
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> if self is not validated_self:</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> warnings.warn(</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> 'A custom validator is returning a value other than `self`.\n'</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> 'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',</pre></li>
<li onclick="toggle('pre133853727867648', 'post133853727867648')"><pre> stacklevel=2,</pre></li>
</ol>
</div>
<details>
<summary class="commands">Local vars</summary>
<table class="vars" id="v133853727867648">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>__tracebackhide__</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>data</td>
<td class="code"><pre>{'message': 'wrong'}</pre></td>
</tr>
<tr>
<td>self</td>
<td class="code"><pre>Pong()</pre></td>
</tr>
</tbody>
</table>
</details>
</li>
</ul>
</div>
<form action="https://dpaste.com/" name="pasteform" id="pasteform" method="post">
<div id="pastebinTraceback" class="pastebin">
<input type="hidden" name="language" value="PythonConsole">
<input type="hidden" name="title"
value="ValidationError at /api/ping/">
<input type="hidden" name="source" value="Django Dpaste Agent">
<input type="hidden" name="poster" value="Django">
<textarea name="content" id="traceback_area" cols="140" rows="25">
Environment:
Request Method: GET
Request URL: http://127.0.0.1:56867/api/ping/
Django Version: 5.2.13
Python Version: 3.12.10
Installed Applications:
['django.contrib.auth',
'django.contrib.sessions',
'django.contrib.contenttypes',
'dmr',
'dmr.security.jwt.blocklist',
'server.apps.model_simple',
'server.apps.model_fk']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/core/handlers/exception.py", line 42, in inner
response = await get_response(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/core/handlers/base.py", line 253, in _get_response_async
response = await wrapped_callback(
File "/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/concurrent/futures/thread.py", line 59, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper
return view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/django/views/generic/base.py", line 105, in view
return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/controller.py", line 224, in dispatch
return endpoint(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 183, in __call__
return self._func( # type: ignore[no-any-return]
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 383, in decorator
func_result = self.handle_error(controller, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 222, in handle_error
return self._global_error_handler(controller, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 482, in _global_error_handler
return resolve_setting( # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/errors.py", line 314, in global_error_handler
raise exc from None
^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 215, in handle_error
return controller.handle_error(
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/controller.py", line 329, in handle_error
raise exc from None
^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/endpoint.py", line 373, in decorator
func_result = func(controller, **context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/docs/examples/error_handling/pydantic_validation_error.py", line 17, in get
return Pong(message='wrong')
^^^^^^^^^^^^^^^^^^^^^
File "/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/envs/0.6.0/lib/python3.12/site-packages/pydantic/main.py", line 250, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Exception Type: ValidationError at /api/ping/
Exception Value: 1 validation error for Pong
message
Input should be 'pong' [type=literal_error, input_value='wrong', input_type=str]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error
</textarea>
<br><br>
<input type="submit" value="Share this traceback on a public website">
</div>
</form>
</div>
<div id="requestinfo">
<h2>Request information</h2>
<h3 id="user-info">USER</h3>
<p>AnonymousUser</p>
<h3 id="get-info">GET</h3>
<p>No GET data</p>
<h3 id="post-info">POST</h3>
<p>No POST data</p>
<h3 id="files-info">FILES</h3>
<p>No FILES data</p>
<h3 id="cookie-info">COOKIES</h3>
<p>No cookie data</p>
<h3 id="meta-info">META</h3>
<table class="req">
<thead>
<tr>
<th scope="col">Variable</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>HTTP_ACCEPT</td>
<td class="code"><pre>'*/*'</pre></td>
</tr>
<tr>
<td>HTTP_HOST</td>
<td class="code"><pre>'127.0.0.1:56867'</pre></td>
</tr>
<tr>
<td>HTTP_USER_AGENT</td>
<td class="code"><pre>'curl/7.81.0'</pre></td>
</tr>
<tr>
<td>PATH_INFO</td>
<td class="code"><pre>'/api/ping/'</pre></td>
</tr>
<tr>
<td>QUERY_STRING</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>REMOTE_ADDR</td>
<td class="code"><pre>'127.0.0.1'</pre></td>
</tr>
<tr>
<td>REMOTE_HOST</td>
<td class="code"><pre>'127.0.0.1'</pre></td>
</tr>
<tr>
<td>REMOTE_PORT</td>
<td class="code"><pre>33590</pre></td>
</tr>
<tr>
<td>REQUEST_METHOD</td>
<td class="code"><pre>'GET'</pre></td>
</tr>
<tr>
<td>SCRIPT_NAME</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>SERVER_NAME</td>
<td class="code"><pre>'127.0.0.1'</pre></td>
</tr>
<tr>
<td>SERVER_PORT</td>
<td class="code"><pre>'56867'</pre></td>
</tr>
<tr>
<td>wsgi.multiprocess</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>wsgi.multithread</td>
<td class="code"><pre>True</pre></td>
</tr>
</tbody>
</table>
<h3 id="settings-info">Settings</h3>
<h4>Using settings module <code></code></h4>
<table class="req">
<thead>
<tr>
<th scope="col">Setting</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>ABSOLUTE_URL_OVERRIDES</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>ADMINS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>ALLOWED_HOSTS</td>
<td class="code"><pre>['*']</pre></td>
</tr>
<tr>
<td>APPEND_SLASH</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>AUTHENTICATION_BACKENDS</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>AUTH_PASSWORD_VALIDATORS</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>AUTH_USER_MODEL</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>CACHES</td>
<td class="code"><pre>{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}</pre></td>
</tr>
<tr>
<td>CACHE_MIDDLEWARE_ALIAS</td>
<td class="code"><pre>'default'</pre></td>
</tr>
<tr>
<td>CACHE_MIDDLEWARE_KEY_PREFIX</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>CACHE_MIDDLEWARE_SECONDS</td>
<td class="code"><pre>600</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_AGE</td>
<td class="code"><pre>31449600</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_DOMAIN</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_HTTPONLY</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_NAME</td>
<td class="code"><pre>'csrftoken'</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_PATH</td>
<td class="code"><pre>'/'</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_SAMESITE</td>
<td class="code"><pre>'Lax'</pre></td>
</tr>
<tr>
<td>CSRF_COOKIE_SECURE</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>CSRF_FAILURE_VIEW</td>
<td class="code"><pre>'django.views.csrf.csrf_failure'</pre></td>
</tr>
<tr>
<td>CSRF_HEADER_NAME</td>
<td class="code"><pre>'HTTP_X_CSRFTOKEN'</pre></td>
</tr>
<tr>
<td>CSRF_TRUSTED_ORIGINS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>CSRF_USE_SESSIONS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>DATABASES</td>
<td class="code"><pre>{'default': {'ATOMIC_REQUESTS': False,
'AUTOCOMMIT': True,
'CONN_HEALTH_CHECKS': False,
'CONN_MAX_AGE': 0,
'ENGINE': 'django.db.backends.sqlite3',
'HOST': '',
'NAME': '_build/test.db',
'OPTIONS': {},
'PASSWORD': '********************',
'PORT': '',
'TEST': {'CHARSET': None,
'COLLATION': None,
'MIGRATE': True,
'MIRROR': None,
'NAME': None},
'TIME_ZONE': None,
'USER': ''}}</pre></td>
</tr>
<tr>
<td>DATABASE_ROUTERS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>DATA_UPLOAD_MAX_MEMORY_SIZE</td>
<td class="code"><pre>2621440</pre></td>
</tr>
<tr>
<td>DATA_UPLOAD_MAX_NUMBER_FIELDS</td>
<td class="code"><pre>1000</pre></td>
</tr>
<tr>
<td>DATA_UPLOAD_MAX_NUMBER_FILES</td>
<td class="code"><pre>100</pre></td>
</tr>
<tr>
<td>DATETIME_FORMAT</td>
<td class="code"><pre>'N j, Y, P'</pre></td>
</tr>
<tr>
<td>DATETIME_INPUT_FORMATS</td>
<td class="code"><pre>['%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M',
'%m/%d/%Y %H:%M:%S',
'%m/%d/%Y %H:%M:%S.%f',
'%m/%d/%Y %H:%M',
'%m/%d/%y %H:%M:%S',
'%m/%d/%y %H:%M:%S.%f',
'%m/%d/%y %H:%M']</pre></td>
</tr>
<tr>
<td>DATE_FORMAT</td>
<td class="code"><pre>'N j, Y'</pre></td>
</tr>
<tr>
<td>DATE_INPUT_FORMATS</td>
<td class="code"><pre>['%Y-%m-%d',
'%m/%d/%Y',
'%m/%d/%y',
'%b %d %Y',
'%b %d, %Y',
'%d %b %Y',
'%d %b, %Y',
'%B %d %Y',
'%B %d, %Y',
'%d %B %Y',
'%d %B, %Y']</pre></td>
</tr>
<tr>
<td>DEBUG</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>DEBUG_PROPAGATE_EXCEPTIONS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>DECIMAL_SEPARATOR</td>
<td class="code"><pre>'.'</pre></td>
</tr>
<tr>
<td>DEFAULT_AUTO_FIELD</td>
<td class="code"><pre>'django.db.models.BigAutoField'</pre></td>
</tr>
<tr>
<td>DEFAULT_CHARSET</td>
<td class="code"><pre>'utf-8'</pre></td>
</tr>
<tr>
<td>DEFAULT_EXCEPTION_REPORTER</td>
<td class="code"><pre>'django.views.debug.ExceptionReporter'</pre></td>
</tr>
<tr>
<td>DEFAULT_EXCEPTION_REPORTER_FILTER</td>
<td class="code"><pre>'django.views.debug.SafeExceptionReporterFilter'</pre></td>
</tr>
<tr>
<td>DEFAULT_FROM_EMAIL</td>
<td class="code"><pre>'webmaster@localhost'</pre></td>
</tr>
<tr>
<td>DEFAULT_INDEX_TABLESPACE</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>DEFAULT_TABLESPACE</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>DISALLOWED_USER_AGENTS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>EMAIL_BACKEND</td>
<td class="code"><pre>'django.core.mail.backends.smtp.EmailBackend'</pre></td>
</tr>
<tr>
<td>EMAIL_HOST</td>
<td class="code"><pre>'localhost'</pre></td>
</tr>
<tr>
<td>EMAIL_HOST_PASSWORD</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>EMAIL_HOST_USER</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>EMAIL_PORT</td>
<td class="code"><pre>25</pre></td>
</tr>
<tr>
<td>EMAIL_SSL_CERTFILE</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>EMAIL_SSL_KEYFILE</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>EMAIL_SUBJECT_PREFIX</td>
<td class="code"><pre>'[Django] '</pre></td>
</tr>
<tr>
<td>EMAIL_TIMEOUT</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>EMAIL_USE_LOCALTIME</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>EMAIL_USE_SSL</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>EMAIL_USE_TLS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_DIRECTORY_PERMISSIONS</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_HANDLERS</td>
<td class="code"><pre>['django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler']</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_MAX_MEMORY_SIZE</td>
<td class="code"><pre>2621440</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_PERMISSIONS</td>
<td class="code"><pre>420</pre></td>
</tr>
<tr>
<td>FILE_UPLOAD_TEMP_DIR</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>FIRST_DAY_OF_WEEK</td>
<td class="code"><pre>0</pre></td>
</tr>
<tr>
<td>FIXTURE_DIRS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>FORCE_SCRIPT_NAME</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>FORMAT_MODULE_PATH</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>FORMS_URLFIELD_ASSUME_HTTPS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>FORM_RENDERER</td>
<td class="code"><pre>'django.forms.renderers.DjangoTemplates'</pre></td>
</tr>
<tr>
<td>HTTP_BASIC_PASSWORD</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>HTTP_BASIC_USERNAME</td>
<td class="code"><pre>'admin'</pre></td>
</tr>
<tr>
<td>IGNORABLE_404_URLS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>INSTALLED_APPS</td>
<td class="code"><pre>['django.contrib.auth',
'django.contrib.sessions',
'django.contrib.contenttypes',
'dmr',
'dmr.security.jwt.blocklist',
'server.apps.model_simple',
'server.apps.model_fk']</pre></td>
</tr>
<tr>
<td>INTERNAL_IPS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>LANGUAGES</td>
<td class="code"><pre>(('en', 'English'), ('ru', 'Russian'))</pre></td>
</tr>
<tr>
<td>LANGUAGES_BIDI</td>
<td class="code"><pre>['he', 'ar', 'ar-dz', 'ckb', 'fa', 'ug', 'ur']</pre></td>
</tr>
<tr>
<td>LANGUAGE_CODE</td>
<td class="code"><pre>'en-us'</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_AGE</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_DOMAIN</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_HTTPONLY</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_NAME</td>
<td class="code"><pre>'django_language'</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_PATH</td>
<td class="code"><pre>'/'</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_SAMESITE</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>LANGUAGE_COOKIE_SECURE</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>LOCALE_PATHS</td>
<td class="code"><pre>['/home/docs/checkouts/readthedocs.org/user_builds/django-modern-rest/checkouts/0.6.0/dmr/locale']</pre></td>
</tr>
<tr>
<td>LOGGING</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>LOGGING_CONFIG</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>LOGIN_REDIRECT_URL</td>
<td class="code"><pre>'/accounts/profile/'</pre></td>
</tr>
<tr>
<td>LOGIN_URL</td>
<td class="code"><pre>'/accounts/login/'</pre></td>
</tr>
<tr>
<td>LOGOUT_REDIRECT_URL</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>MANAGERS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>MEDIA_ROOT</td>
<td class="code"><pre>''</pre></td>
</tr>
<tr>
<td>MEDIA_URL</td>
<td class="code"><pre>'/'</pre></td>
</tr>
<tr>
<td>MESSAGE_STORAGE</td>
<td class="code"><pre>'django.contrib.messages.storage.fallback.FallbackStorage'</pre></td>
</tr>
<tr>
<td>MIDDLEWARE</td>
<td class="code"><pre>['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']</pre></td>
</tr>
<tr>
<td>MIGRATION_MODULES</td>
<td class="code"><pre>{}</pre></td>
</tr>
<tr>
<td>MONTH_DAY_FORMAT</td>
<td class="code"><pre>'F j'</pre></td>
</tr>
<tr>
<td>NUMBER_GROUPING</td>
<td class="code"><pre>0</pre></td>
</tr>
<tr>
<td>PASSWORD_HASHERS</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>PASSWORD_RESET_TIMEOUT</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>PREPEND_WWW</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>ROOT_URLCONF</td>
<td class="code"><pre>'url_conf'</pre></td>
</tr>
<tr>
<td>SECRET_KEY</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>SECRET_KEY_FALLBACKS</td>
<td class="code"><pre>'********************'</pre></td>
</tr>
<tr>
<td>SECURE_CONTENT_TYPE_NOSNIFF</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>SECURE_CROSS_ORIGIN_OPENER_POLICY</td>
<td class="code"><pre>'same-origin'</pre></td>
</tr>
<tr>
<td>SECURE_HSTS_INCLUDE_SUBDOMAINS</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SECURE_HSTS_PRELOAD</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SECURE_HSTS_SECONDS</td>
<td class="code"><pre>0</pre></td>
</tr>
<tr>
<td>SECURE_PROXY_SSL_HEADER</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>SECURE_REDIRECT_EXEMPT</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>SECURE_REFERRER_POLICY</td>
<td class="code"><pre>'same-origin'</pre></td>
</tr>
<tr>
<td>SECURE_SSL_HOST</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>SECURE_SSL_REDIRECT</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SERVER_EMAIL</td>
<td class="code"><pre>'root@localhost'</pre></td>
</tr>
<tr>
<td>SESSION_CACHE_ALIAS</td>
<td class="code"><pre>'default'</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_AGE</td>
<td class="code"><pre>1209600</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_DOMAIN</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_HTTPONLY</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_NAME</td>
<td class="code"><pre>'sessionid'</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_PATH</td>
<td class="code"><pre>'/'</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_SAMESITE</td>
<td class="code"><pre>'Lax'</pre></td>
</tr>
<tr>
<td>SESSION_COOKIE_SECURE</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SESSION_ENGINE</td>
<td class="code"><pre>'django.contrib.sessions.backends.db'</pre></td>
</tr>
<tr>
<td>SESSION_EXPIRE_AT_BROWSER_CLOSE</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SESSION_FILE_PATH</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>SESSION_SAVE_EVERY_REQUEST</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>SESSION_SERIALIZER</td>
<td class="code"><pre>'django.contrib.sessions.serializers.JSONSerializer'</pre></td>
</tr>
<tr>
<td>SHORT_DATETIME_FORMAT</td>
<td class="code"><pre>'m/d/Y P'</pre></td>
</tr>
<tr>
<td>SHORT_DATE_FORMAT</td>
<td class="code"><pre>'m/d/Y'</pre></td>
</tr>
<tr>
<td>SIGNING_BACKEND</td>
<td class="code"><pre>'django.core.signing.TimestampSigner'</pre></td>
</tr>
<tr>
<td>SILENCED_SYSTEM_CHECKS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>STATICFILES_DIRS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>STATICFILES_FINDERS</td>
<td class="code"><pre>['django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder']</pre></td>
</tr>
<tr>
<td>STATIC_ROOT</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>STATIC_URL</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>STORAGES</td>
<td class="code"><pre>{'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage'},
'staticfiles': {'BACKEND': 'django.contrib.staticfiles.storage.StaticFilesStorage'}}</pre></td>
</tr>
<tr>
<td>TEMPLATES</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>TEST_NON_SERIALIZED_APPS</td>
<td class="code"><pre>[]</pre></td>
</tr>
<tr>
<td>TEST_RUNNER</td>
<td class="code"><pre>'django.test.runner.DiscoverRunner'</pre></td>
</tr>
<tr>
<td>THOUSAND_SEPARATOR</td>
<td class="code"><pre>','</pre></td>
</tr>
<tr>
<td>TIME_FORMAT</td>
<td class="code"><pre>'P'</pre></td>
</tr>
<tr>
<td>TIME_INPUT_FORMATS</td>
<td class="code"><pre>['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']</pre></td>
</tr>
<tr>
<td>TIME_ZONE</td>
<td class="code"><pre>'America/Chicago'</pre></td>
</tr>
<tr>
<td>USE_I18N</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>USE_THOUSAND_SEPARATOR</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>USE_TZ</td>
<td class="code"><pre>True</pre></td>
</tr>
<tr>
<td>USE_X_FORWARDED_HOST</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>USE_X_FORWARDED_PORT</td>
<td class="code"><pre>False</pre></td>
</tr>
<tr>
<td>WSGI_APPLICATION</td>
<td class="code"><pre>None</pre></td>
</tr>
<tr>
<td>X_FRAME_OPTIONS</td>
<td class="code"><pre>'DENY'</pre></td>
</tr>
<tr>
<td>YEAR_MONTH_FORMAT</td>
<td class="code"><pre>'F Y'</pre></td>
</tr>
</tbody>
</table>
</div>
</main>
<footer id="explanation">
<p>
You’re seeing this error because you have <code>DEBUG = True</code> in your
Django settings file. Change that to <code>False</code>, and Django will
display a standard page generated by the handler for this status code.
</p>
</footer>
</body>
</html>
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:
1from http import HTTPStatus
2from typing import Literal
3
4import pydantic
5from django.http import HttpResponse
6from typing_extensions import override
7
8from dmr import Controller, ResponseSpec
9from dmr.endpoint import Endpoint
10from dmr.plugins.pydantic import PydanticSerializer
11
12
13class Pong(pydantic.BaseModel):
14 message: Literal['pong']
15
16
17class PongController(Controller[PydanticSerializer]):
18 responses = (
19 ResponseSpec(
20 Controller.error_model,
21 status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
22 ),
23 )
24
25 def get(self) -> Pong:
26 # This will trigger `pydantic.ValidationError`,
27 # because `message` must be `'pong'`, not `'wrong'`:
28 return Pong(message='wrong')
29
30 @override
31 def handle_error(
32 self,
33 endpoint: Endpoint,
34 controller: Controller[PydanticSerializer],
35 exc: Exception,
36 ) -> HttpResponse:
37 if isinstance(exc, pydantic.ValidationError):
38 # Now, handle the error, but do not show what actually happened
39 # to the outside world, it might contain sensitive data:
40 return self.to_response(
41 self.format_error('Validation error'),
42 status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
43 )
44 return super().handle_error(endpoint, controller, exc)
45
Run result
$ curl http://127.0.0.1:8000/api/ping/ -D - -X GET
HTTP/1.1 500 Internal Server Error
date: Thu, 09 Apr 2026 14:41:30 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:
Per endpoint configuration via
handle_error()andhandle_async_error()methodsPer controller handlers
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:
HttpResponsewith proper response for this error. Or raise exc back.
Here’s an example that will produce
{'detail': [{'msg': 'inf', 'type': 'user_msg'}]}for anyZeroDivisionErrorin 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_handlerin 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.
- 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]¶
Default error response schema.
Can be customized. See Customizing error messages for more details.
- 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:
Direct usage: you raise an error and get what you raise, no changes
Conditional usage: you call
conditional_errormethod and if the client acceptsapplication/problem+json, we will return the proper Problem Details description. But, if it is not requested directly, we will return our regulardmr.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+jsonthen return a Problem Details exception. If not, return regulardmr.response.APIErrorinstance.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, useProblemDetailsModeldirectly.
- 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.
- 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.