Beispiel #1
0
 def inner(request):
     try:
         response = get_response(request)
     except TimeoutError as exc:
         log.warning(
             f'Timeout: {request.path}',
             extra={
                 'status_code': 408,
                 'request': request
             },
         )
         resolver = get_resolver(get_urlconf())
         response = get_exception_response(request, resolver, 408, exc)
     except Exception as exc:
         response = response_for_exception(request, exc)
     return response
Beispiel #2
0
    def process_exception(request, exception):
        exception_json = {'error': _get_exception_message(exception)}
        status = _get_exception_status_code(exception)
        if exception.__class__ in ERROR_LOG_EXCEPTIONS:
            exception_json['log_error'] = True
        if DEBUG or status == 500:
            traceback_message = traceback.format_exc()
            exception_json['traceback'] = traceback_message
        detail = getattr(exception, 'info', None)
        if isinstance(detail, dict):
            exception_json['detail'] = detail

        if request.path.startswith('/api'):
            return create_json_response(exception_json, status=status)

        response = get_exception_response(request, get_resolver(get_urlconf()),
                                          status, exception)
        response.data = exception_json
        # LogRequestMiddleware will handle logging for this so do not use standard request logging
        response._has_been_logged = True
        return response
Beispiel #3
0
 def process_exception(self, request, exception):
     encoding = "utf-8"
     if isinstance(exception, MAASAPIException):
         # Print a traceback if this is a 500 error.
         if (settings.DEBUG or exception.api_error
                 == http.client.INTERNAL_SERVER_ERROR):
             self.log_exception(exception)
         # This type of exception knows how to translate itself into
         # an http response.
         return exception.make_http_response()
     elif isinstance(exception, ValidationError):
         if settings.DEBUG:
             self.log_exception(exception)
         if hasattr(exception, "message_dict"):
             # Complex validation error with multiple fields:
             # return a json version of the message_dict.
             return HttpResponseBadRequest(
                 json.dumps(exception.message_dict),
                 content_type="application/json",
             )
         else:
             # Simple validation error: return the error message.
             return HttpResponseBadRequest(
                 str("".join(exception.messages)).encode(encoding),
                 content_type="text/plain; charset=%s" % encoding,
             )
     elif isinstance(exception, PermissionDenied):
         if settings.DEBUG:
             self.log_exception(exception)
         return HttpResponseForbidden(
             content=str(exception).encode(encoding),
             content_type="text/plain; charset=%s" % encoding,
         )
     elif isinstance(exception, ExternalProcessError):
         # Catch problems interacting with processes that the
         # appserver spawns, e.g. rndc.
         #
         # While this is a serious error, it should be a temporary
         # one as the admin should be checking and fixing, or it
         # could be spurious.  There's no way of knowing, so the best
         # course of action is to ask the caller to repeat.
         if settings.DEBUG:
             self.log_exception(exception)
         response = HttpResponse(
             content=str(exception).encode(encoding),
             status=int(http.client.SERVICE_UNAVAILABLE),
             content_type="text/plain; charset=%s" % encoding,
         )
         response["Retry-After"] = RETRY_AFTER_SERVICE_UNAVAILABLE
         return response
     elif isinstance(exception, Http404):
         if settings.DEBUG:
             self.log_exception(exception)
         return get_exception_response(request, get_resolver(get_urlconf()),
                                       404, exception)
     elif is_retryable_failure(exception):
         # We never handle retryable failures.
         return None
     elif isinstance(exception, SystemExit):
         return None
     else:
         # Print a traceback.
         self.log_exception(exception)
         # Return an API-readable "Internal Server Error" response.
         return HttpResponse(
             content=str(exception).encode(encoding),
             status=int(http.client.INTERNAL_SERVER_ERROR),
             content_type="text/plain; charset=%s" % encoding,
         )