|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from __future__ import unicode_literals |
| 3 | + |
| 4 | +from django import forms |
| 5 | +from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied |
| 6 | +from django.forms.utils import ErrorDict, ErrorList |
| 7 | +from django.http import Http404 |
| 8 | + |
| 9 | +import six |
| 10 | + |
| 11 | +from rest_framework import exceptions |
| 12 | +from rest_framework.response import Response |
| 13 | +from rest_framework.settings import api_settings |
| 14 | + |
| 15 | + |
| 16 | +def _reformat_drf_errors(errors, detail, path=None): |
| 17 | + if path is None: |
| 18 | + path = [] |
| 19 | + if isinstance(detail, dict): |
| 20 | + for k, v in detail.items(): |
| 21 | + if k == api_settings.NON_FIELD_ERRORS_KEY: |
| 22 | + new_path = path |
| 23 | + else: |
| 24 | + new_path = path + [k] |
| 25 | + _reformat_drf_errors(errors, v, new_path) |
| 26 | + elif isinstance(detail, list): |
| 27 | + for idx, v in enumerate(detail): |
| 28 | + if v: |
| 29 | + _reformat_drf_errors(errors, v, path + ['{}'.format(idx)]) |
| 30 | + else: |
| 31 | + # errors are always coerced to a list so we |
| 32 | + # can skip the last level in our path |
| 33 | + path.pop() |
| 34 | + message = six.text_type(detail) |
| 35 | + error = { |
| 36 | + 'message': message, |
| 37 | + 'code': getattr(detail, 'code', 'invalid') or 'invalid', |
| 38 | + } |
| 39 | + # do not put a field attribute on global validaiton errors |
| 40 | + if path: |
| 41 | + error['field'] = '.'.join(path) |
| 42 | + errors.append(error) |
| 43 | + |
| 44 | + |
| 45 | +def format_validation_error(detail): |
| 46 | + errors = [] |
| 47 | + _reformat_drf_errors(errors, detail) |
| 48 | + return { |
| 49 | + 'code': 'validation_error', |
| 50 | + 'message': 'Validation failed', |
| 51 | + 'errors': errors, |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | +def _reformat_forms_errors(errors, error, path=None): |
| 56 | + if path is None: |
| 57 | + path = [] |
| 58 | + if isinstance(error, ErrorDict): |
| 59 | + for k, v in error.items(): |
| 60 | + if k == NON_FIELD_ERRORS: |
| 61 | + new_path = path |
| 62 | + else: |
| 63 | + new_path = path + [k] |
| 64 | + _reformat_forms_errors(errors, v, new_path) |
| 65 | + elif isinstance(error, ErrorList): |
| 66 | + for item in error.as_data(): |
| 67 | + _reformat_forms_errors(errors, item, path) |
| 68 | + elif isinstance(error, list): |
| 69 | + for item in error: |
| 70 | + _reformat_forms_errors(errors, item, path) |
| 71 | + else: |
| 72 | + # django.core.exceptions.Exception |
| 73 | + item = { |
| 74 | + 'message': six.text_type(error.message), |
| 75 | + 'code': error.code or 'invalid', |
| 76 | + } |
| 77 | + if path: |
| 78 | + item['field'] = '.'.join(path) |
| 79 | + errors.append(item) |
| 80 | + |
| 81 | + |
| 82 | +def format_forms_error(error): |
| 83 | + errors = [] |
| 84 | + _reformat_forms_errors(errors, error) |
| 85 | + return { |
| 86 | + 'code': 'validation_error', |
| 87 | + 'message': 'Validation failed', |
| 88 | + 'errors': errors, |
| 89 | + } |
| 90 | + |
| 91 | + |
| 92 | +def exception_handler(exc, context): |
| 93 | + """ |
| 94 | + Returns the response that should be used for any given exception. |
| 95 | +
|
| 96 | + By default we handle the REST framework `APIException`, and also |
| 97 | + Django's built-in `Http404` and `PermissionDenied` exceptions. |
| 98 | +
|
| 99 | + Any unhandled exceptions may return `None`, which will cause a 500 error |
| 100 | + to be raised. |
| 101 | + """ |
| 102 | + headers = None |
| 103 | + if isinstance(exc, exceptions.ValidationError): |
| 104 | + data = format_validation_error(exc.detail) |
| 105 | + # change default 400 status code from DRF to Unprocessable Entity |
| 106 | + status_code = 422 |
| 107 | + # status_code = exc.status_code |
| 108 | + elif isinstance(exc, exceptions.APIException): |
| 109 | + headers = {} |
| 110 | + if getattr(exc, 'auth_header', None): |
| 111 | + headers['WWW-Authenticate'] = exc.auth_header |
| 112 | + if getattr(exc, 'wait', None): |
| 113 | + headers['Retry-After'] = '%d' % exc.wait |
| 114 | + |
| 115 | + data = { |
| 116 | + 'code': getattr(exc.detail, 'code', 'error'), |
| 117 | + 'message': six.text_type(exc.detail), |
| 118 | + } |
| 119 | + status_code = exc.status_code |
| 120 | + elif isinstance(exc, Http404): |
| 121 | + data = { |
| 122 | + 'code': 'not_found', |
| 123 | + 'message': six.text_type(exceptions.NotFound.default_detail), |
| 124 | + } |
| 125 | + status_code = 404 |
| 126 | + elif isinstance(exc, PermissionDenied): |
| 127 | + data = { |
| 128 | + 'code': 'permission_denied', |
| 129 | + 'message': six.text_type( |
| 130 | + exceptions.PermissionDenied.default_detail), |
| 131 | + } |
| 132 | + status_code = 403 |
| 133 | + elif isinstance(exc, forms.ValidationError): |
| 134 | + data = format_forms_error(exc.error_list) |
| 135 | + status_code = 422 |
| 136 | + else: |
| 137 | + # unhandled exception, return generic error |
| 138 | + # TODO add logs ? |
| 139 | + data = { |
| 140 | + 'code': 'error', |
| 141 | + 'message': six.text_type( |
| 142 | + exceptions.APIException.default_detail), |
| 143 | + } |
| 144 | + status_code = 500 |
| 145 | + |
| 146 | + return Response(data, status=status_code, headers=headers) |
| 147 | + |
| 148 | + |
| 149 | +class ExceptionHandlerMixin(object): |
| 150 | + """ |
| 151 | + this mixin replaces the exception handler from the APIView |
| 152 | +
|
| 153 | + Warning: must be set *after* `CallbackMixin`. |
| 154 | + """ |
| 155 | + |
| 156 | + def handle_exception(self, exc): |
| 157 | + """ |
| 158 | + Handle any exception that occurs, by returning an appropriate response, |
| 159 | + or re-raising the error. |
| 160 | + """ |
| 161 | + if isinstance(exc, (exceptions.NotAuthenticated, |
| 162 | + exceptions.AuthenticationFailed)): |
| 163 | + # WWW-Authenticate header for 401 responses, else coerce to 403 |
| 164 | + auth_header = self.get_authenticate_header(self.request) |
| 165 | + |
| 166 | + if auth_header: |
| 167 | + exc.auth_header = auth_header |
| 168 | + else: |
| 169 | + exc.status_code = 403 |
| 170 | + |
| 171 | + context = self.get_exception_handler_context() |
| 172 | + response = exception_handler(exc, context) |
| 173 | + |
| 174 | + if response is None: |
| 175 | + raise |
| 176 | + |
| 177 | + response.exception = True |
| 178 | + return response |
0 commit comments