aboutsummaryrefslogtreecommitdiffstats
path: root/docs/api-guide/exceptions.md
blob: 66e181737743df6394fec41948e08538897b3e65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<a class="github" href="exceptions.py"></a>

# Exceptions

> Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.
>
> &mdash; Doug Hellmann, [Python Exception Handling Techniques][cite]

## Exception handling in REST framework views

REST framework's views handle various exceptions, and deal with returning appropriate error responses.

The handled exceptions are:

* Subclasses of `APIException` raised inside REST framework.
* Django's `Http404` exception.
* Django's `PermissionDenied` exception.

In each case, REST framework will return a response with an appropriate status code and content-type.  The body of the response will include any additional details regarding the nature of the error.

By default all error responses will include a key `detail` in the body of the response, but other keys may also be included.

For example, the following request:

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

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

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

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

## Custom exception handling

You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects.  This allows you to control the style of error responses used by your API.

The function must take a single argument, which is the exception to be handled, and should either return a `Response` object, or return `None` if the exception cannot be handled.  If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.

For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:

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

    {"status_code": 405, "detail": "Method 'DELETE' not allowed."}

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

    from rest_framework.views import exception_handler

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

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

        return response

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

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

If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard exception handler provided by REST framework:

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
    }

Note that the exception handler will only be called for responses generated by raised exceptions.  It will not be used for any responses returned directly by the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the generic views when serializer validation fails.

---

# API Reference

## APIException

**Signature:** `APIException()`

The **base class** for all exceptions raised inside REST framework.

To provide a custom exception, subclass `APIException` and set the `.status_code` and `.default_detail` properties on the class.

For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code.  You could do this like so:

    from rest_framework.exceptions import APIException

    class ServiceUnavailable(APIException):
        status_code = 503
        default_detail = 'Service temporarily unavailable, try again later.'

## ParseError

**Signature:** `ParseError(detail=None)`

Raised if the request contains malformed data when accessing `request.DATA` or `request.FILES`.

By default this exception results in a response with the HTTP status code "400 Bad Request".

## AuthenticationFailed

**Signature:** `AuthenticationFailed(detail=None)`

Raised when an incoming request includes incorrect authentication.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use.  See the [authentication documentation][authentication] for more details.

## NotAuthenticated

**Signature:** `NotAuthenticated(detail=None)`

Raised when an unauthenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use.  See the [authentication documentation][authentication] for more details.

## PermissionDenied

**Signature:** `PermissionDenied(detail=None)`

Raised when an authenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code "403 Forbidden".

## MethodNotAllowed

**Signature:** `MethodNotAllowed(method, detail=None)`

Raised when an incoming request occurs that does not map to a handler method on the view.

By default this exception results in a response with the HTTP status code "405 Method Not Allowed".

## UnsupportedMediaType

**Signature:** `UnsupportedMediaType(media_type, detail=None)`

Raised if there are no parsers that can handle the content type of the request data when accessing `request.DATA` or `request.FILES`.

By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".

## Throttled

**Signature:** `Throttled(wait=None, detail=None)`

Raised when an incoming request fails the throttling checks.

By default this exception results in a response with the HTTP status code "429 Too Many Requests".

[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
[authentication]: authentication.md
='n435' href='#n435'>435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663