Fetches and executes an exception handler and returns a response
        object

        :param request: Request
        :param exception: Exception to handle
        :return: Response object
439830
def response(self, request, exception):
        
        handler = self.lookup(exception)
        response = None
        try:
            if handler:
                response = handler(request=request, exception=exception)
            if response is None:
                response = self.default(request=request, exception=exception)
        except Exception:
            self.log(format_exc())
            if self.debug:
                url = getattr(request, 'url', 'unknown')
                response_message = (
                    'Exception raised in exception handler "{}" '
                    'for uri: "{}"\n{}').format(
                        handler.__name__, url, format_exc())
                self._log.error(response_message)
                return text(response_message, 500)
            else:
                return text('An error occurred while handling an error', 500)
        return response
1120925
private HttpResponse executeRequest(HttpPost request) throws Exception {
        try {
            HttpClient httpClient = connection.getHttpClient();
            HttpContext httpContext = connection.getHttpContext();
            HttpResponse response = httpClient.execute(request, httpContext);
            return response;
        } catch (Exception e) {
            throw MwsUtl.wrap(e);
        }
    }
1275641
async def handle_exception(self, exc: Exception, action: str, request_id):
        
        if isinstance(exc, APIException):
            await self.reply(
                action=action,
                errors=self._format_errors(exc.detail),
                status=exc.status_code,
                request_id=request_id
            )
        elif exc == Http404 or isinstance(exc, Http404):
            await self.reply(
                action=action,
                errors=self._format_errors('Not found'),
                status=404,
                request_id=request_id
            )
        else:
            raise exc
141973
def _handle_request(self, request):
        """"""
        if 'types' in self.method_data[request['method']]:
            self._validate_params_types(request['method'], request['params'])

        if self.serve_exception:
            raise self.serve_exception()
        d = self._call_method(request)
        self.pending.add(d)
        if self.timeout:
            timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)

            def completed(result):
                if timeout_deferred.active():
                    # cancel the timeout_deferred if it has not been fired yet
                    # this is to prevent d's deferred chain from firing twice
                    # (and raising an exception).
                    timeout_deferred.cancel()
                return result
            d.addBoth(completed)
        try:
            result = yield d
        except defer.CancelledError:
            # The request was cancelled due to a timeout or by cancelPending
            # having been called. We return a TimeoutError to the client.
            self._remove_pending(d)
            raise TimeoutError()
        except Exception as e:
            self._remove_pending(d)
            raise e
        self._remove_pending(d)
        # Do not respond to notifications.
        if request['id'] is None:
            defer.returnValue(None)

        respond = {}
        self._fill_ver(request['jsonrpc'], respond)
        respond['result'] = result
        respond['id'] = request['id']

        defer.returnValue(respond)
114009
def request_exception(sender, request, **kwargs):
    
    if not isinstance(request, WSGIRequest):
        logger = logging.getLogger(__name__)
        level = CRITICAL if request.status_code <= 500 else WARNING

        logger.log(level, '%s exception occured (%s)',
                   request.status_code, request.reason_phrase)

    else:
        logger = logging.getLogger(__name__)
        logger.log(WARNING, 'WSGIResponse exception occured')
360933
def handle_exception(self, exc):
        
        if isinstance(exc, (exceptions.NotAuthenticated,
                            exceptions.AuthenticationFailed)):
            # WWW-Authenticate header for 401 responses, else coerce to 403
            auth_header = self.get_authenticate_header(self.request)

            if auth_header:
                exc.auth_header = auth_header
            else:
                exc.status_code = status.HTTP_403_FORBIDDEN

        exception_handler = self.settings.EXCEPTION_HANDLER

        context = self.get_exception_handler_context()
        response = exception_handler(exc, context)

        if response is None:
            raise

        response.exception = True
        return response
789899
def handle_request(self, request, **resources):
        
        if not request.method in self._meta.callmap.keys():
            raise HttpError(
                'Unknown or unsupported method \'%s\'' % request.method,
                status=status.HTTP_501_NOT_IMPLEMENTED)

        # Get the appropriate create/read/update/delete function
        view = getattr(self, self._meta.callmap[request.method])

        # Get function data
        return view(request, **resources)
992282
def _handle_client_exception():
    
    try:
        yield

    except _ClientException as exception:
        if exception.http_status in _ERROR_CODES:
            raise _ERROR_CODES[exception.http_status](
                exception.http_reason)
        raise
1054764
def _handle_request_exception(request):
        """"""
        try:
            data = request.json()
        except:
            data = {}

        code = request.status_code
        if code == requests.codes.bad:
            raise BadRequestException(response=data)

        if code == requests.codes.unauthorized:
            raise UnauthorizedException(response=data)

        if code == requests.codes.not_found:
            raise NotFoundException(response=data)

        # Generic error fallback
        request.raise_for_status()
702822
async def finalize_request(
        self,
        result: ResponseReturnValue,
        request_context: Optional[RequestContext]=None,
        from_error_handler: bool=False,
    ) -> Response:
        
        response = await self.make_response(result)
        try:
            response = await self.process_response(response, request_context)
            await request_finished.send(self, response=response)
        except Exception:
            if not from_error_handler:
                raise
            self.logger.exception('Request finalizing errored')
        return response
66522
def create_api_error_from_http_exception(e):
    
    response = e.response
    try:
        explanation = response.json()['message']
    except ValueError:
        explanation = (response.content or '').strip()
    cls = APIError
    if response.status_code == 404:
        if explanation and ('No such image' in str(explanation) or
                            'not found: does not exist or no pull access'
                            in str(explanation) or
                            'repository does not exist' in str(explanation)):
            cls = ImageNotFound
        else:
            cls = NotFound
    raise cls(e, response=response, explanation=explanation)
481471
def _make_request(self, request):
        
        # TODO: I'm sure all kinds of error checking needs to go here
        try:
            response_raw = urllib2.urlopen(request)
        except urllib2.HTTPError, e:
            print e.read()
            raise

        response_str = response_raw.read()
        response = json.loads(response_str)

        self._last_request = request
        self._last_response = response_raw
        self._last_response_str = response_str
        return response
631655
def _handle_request_exc(exc, retry_timeout_config):
    
    if isinstance(exc, requests.exceptions.ConnectTimeout):
        raise ConnectTimeout(_request_exc_message(exc), exc,
                             retry_timeout_config.connect_timeout,
                             retry_timeout_config.connect_retries)
    elif isinstance(exc, requests.exceptions.ReadTimeout):
        raise ReadTimeout(_request_exc_message(exc), exc,
                          retry_timeout_config.read_timeout,
                          retry_timeout_config.read_retries)
    elif isinstance(exc, requests.exceptions.RetryError):
        raise RetriesExceeded(_request_exc_message(exc), exc,
                              retry_timeout_config.connect_retries)
    else:
        raise ConnectionError(_request_exc_message(exc), exc)
249504
def process_exception(self, request, e):
        
        if isinstance(e, RedirectException):
            response = e.get_response()
            self.process_response(request, response)
1257817
def exception_handle(method):
    """"""

    def wrapper(*args, **kwargs):
        try:
            result = method(*args, **kwargs)
            return result
        except ProxyError:
            LOG.exception('ProxyError when try to get %s.', args)
            raise ProxyError('A proxy error occurred.')
        except ConnectionException:
            LOG.exception('ConnectionError when try to get %s.', args)
            raise ConnectionException('DNS failure, refused connection, etc.')
        except Timeout:
            LOG.exception('Timeout when try to get %s', args)
            raise Timeout('The request timed out.')
        except RequestException:
            LOG.exception('RequestException when try to get %s.', args)
            raise RequestException('Please check out your network.')

    return wrapper
798664
def handle_exception(self, e, request=None):
        
        if isinstance(e, HttpError):
            response = SerializedHttpResponse(e.content, status=e.status)
            return self.emit(
                response, request=request, emitter=e.emitter)

        if isinstance(e, (AssertionError, ValidationError)):

            content = unicode(e)

            if isinstance(e, FormError):
                content = e.form.errors

            response = SerializedHttpResponse(
                content, status=status.HTTP_400_BAD_REQUEST)

            return self.emit(response, request=request)

        if ADREST_DEBUG:
            raise

        logger.exception('\nADREST API Error: %s', request.path)

        return HttpResponse(str(e), status=500)
165903
private function unhandledExceptionResponse(ServerRequestInterface $request, Throwable $exception): ResponseInterface
    {
        // Create a stack dump for the exception
        $base_path = dirname(__DIR__, 3);
        $trace     = $exception->getMessage() . PHP_EOL . $exception->getTraceAsString();
        $trace     = str_replace($base_path, '…', $trace);

        try {
            Log::addErrorLog($trace);
        } catch (Throwable $exception) {
            // Must have been a problem with the database.  Nothing we can do here.
        }

        if ($request->getHeaderLine('X-Requested-With') !== '') {
            // If this was a GET request, then we were probably fetching HTML to display, for
            // example a chart or tab.
            if ($request->getMethod() === self::METHOD_GET) {
                $status_code = self::STATUS_OK;
            } else {
                $status_code = self::STATUS_INTERNAL_SERVER_ERROR;
            }

            return response(view('components/alert-danger', ['alert' => $trace]), $status_code);
        }

        return $this->viewResponse('errors/unhandled-exception', [
            'title' => 'Error',
            'error' => $trace,
        ], self::STATUS_INTERNAL_SERVER_ERROR);
    }