Dispatch a request with error handling.
343013
def dispatch!
      # Avoid passing frozen string in force_encoding
      @params.merge!(@request.params).each do |key, val|
        next unless val.respond_to?(:force_encoding)
        val = val.dup if val.frozen?
        @params[key] = force_encoding(val)
      end

      invoke do
        static! if settings.static? && (request.get? || request.head?)
        filter! :before
        route!
      end
    rescue ::Exception => boom
      invoke { handle_exception!(boom) }
    ensure
      begin
        filter! :after unless env['sinatra.static_file']
      rescue ::Exception => boom
        invoke { handle_exception!(boom) } unless @env['sinatra.error']
      end
    end
114226
function handleError(e, done) {
    if(this.defaultValue) return done(null, this.defaultValue);
    if(this[defaultError]) return done(this[defaultError]);
    done(e);
  }
339969
def request(self, msgtype, msgid, method, params=[]):
        """"""
        result = None
        error = None
        exception = None

        try:
            result = self.dispatch.call(method, params)
        except Exception as e:
            error = (e.__class__.__name__, str(e))
            exception = e

        if isinstance(result, Deferred):
            result.add_callback(self._result, msgid)
            result.add_errback(self._error, msgid)
        else:
            self.send_response(msgid, error, result)
1096894
def handle_error(self, request: Any, status: int = 500, exc: Any = None, message: Optional[str] = None) -> web.Response:
        """"""
        if self.transport is None:
            # client has been disconnected during writing.
            if self._access_log:
                request_ip = RequestHandler.get_request_ip(request, None)
                version_string = None
                if isinstance(request.version, HttpVersion):
                    version_string = 'HTTP/{}.{}'.format(request.version.major, request.version.minor)
                logging.getLogger('transport.http').info('[{}] [{}] {} {} "{} {}{}{}" - {} "{}" -'.format(
                    RequestHandler.colorize_status('http', 499),
                    RequestHandler.colorize_status(499),
                    request_ip or '',
                    '"{}"'.format(request._cache['auth'].login.replace('"', '')) if request._cache.get('auth') and getattr(request._cache.get('auth'), 'login', None) else '-',
                    request.method,
                    request.path,
                    '?{}'.format(request.query_string) if request.query_string else '',
                    ' {}'.format(version_string) if version_string else '',
                    request.content_length if request.content_length is not None else '-',
                    request.headers.get('User-Agent', '').replace('"', '')
                ))

        headers = {}
        headers[hdrs.CONTENT_TYPE] = 'text/plain; charset=utf-8'

        msg = '' if status == 500 or not message else message

        headers[hdrs.CONTENT_LENGTH] = str(len(msg))
        headers[hdrs.SERVER] = self._server_header or ''
        resp = web.Response(status=status,  # type: ignore
                            text=msg,
                            headers=headers)  # type: web.Response
        resp.force_close()  # type: ignore

        # some data already got sent, connection is broken
        if request.writer.output_size > 0 or self.transport is None:
            self.force_close()  # type: ignore
        elif self.transport is not None:
            request_ip = RequestHandler.get_request_ip(request, None)
            if not request_ip:
                peername = request.transport.get_extra_info('peername')
                if peername:
                    request_ip, _ = peername
            if self._access_log:
                logging.getLogger('transport.http').info('[{}] [{}] {} {} "INVALID" {} - "" -'.format(
                    RequestHandler.colorize_status('http', status),
                    RequestHandler.colorize_status(status),
                    request_ip or '',
                    '"{}"'.format(request._cache['auth'].login.replace('"', '')) if request._cache.get('auth') and getattr(request._cache.get('auth'), 'login', None) else '-',
                    len(msg)
                ))

        return resp
1024698
def handle_error(self, error=None):
        """"""
        if _debug: TCPClientActor._debug("handle_error %r", error)

        # pass along to the director
        if error is not None:
            self.director.actor_error(self, error)
        else:
            TCPClient.handle_error(self)
595085
public void dispatch(Request request, Response response) throws IOException, ServletException {
        onPreDispatch(request, response);
        onRouteDispatch(request, response);
        onPostDispatch(request, response);
    }
831131
void error(ServletRequest servletRequest,
                        ServletResponse servletResponse)
        throws ServletException,IOException
    {
        dispatch(servletRequest,servletResponse,Dispatcher.__ERROR);
    }
345700
private void handleResponseError(long requestId, Throwable error) {
    ContextualFuture future = futures.remove(requestId);
    if (future != null) {
      future.context.execute(() -> future.completeExceptionally(error));
    }
  }
190168
protected function dispatch()
    {
        // Start processing the requests.
        list($mrc, $active) = $this->process();

        // Keep processing requests until we're done.
        while ($active and $mrc === CURLM_OK) {
            // Process the next request.
            list($mrc, $active) = $this->process();
        }

        // Throw an exception if something went wrong.
        if ($mrc !== CURLM_OK) {
            throw new CurlErrorException('cURL read error #'.$mrc);
        }
    }
327324
def dispatch(self, request, *args, **kwargs):
        
        allowed_methods = self.get_allowed_methods()
        try:
            if request.method == 'GET' and 'GET' in allowed_methods:
                if 'pk' in request.GET or self.slug_field in request.GET:
                    return self.ng_get(request, *args, **kwargs)
                return self.ng_query(request, *args, **kwargs)
            elif request.method == 'POST' and 'POST' in allowed_methods:
                return self.ng_save(request, *args, **kwargs)
            elif request.method == 'DELETE' and 'DELETE' in allowed_methods:
                return self.ng_delete(request, *args, **kwargs)
        except self.model.DoesNotExist as e:
            return self.error_json_response(e.args[0], 404)
        except NgMissingParameterError as e:
            return self.error_json_response(e.args[0])
        except JSONResponseException as e:
            return self.error_json_response(e.args[0], e.status_code)
        except ValidationError as e:
            if hasattr(e, 'error_dict'):
                return self.error_json_response('Form not valid', detail=e.message_dict)
            else:
                return self.error_json_response(e.message)

        return self.error_json_response('This view can not handle method {0}'.format(request.method), 405)
1306117
def dispatch_command(self, command, params=None):
        """"""
        try:
            if command in self.handlers:
                self.handlers[command](**params)
            else:
                logging.warning('Unsupported command: %s: %s',
                                command, params)
        except Exception as e:
            logging.warning('Error during command execution',
                            exc_info=sys.exc_info())
            raise e
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)
1254571
def handleError(self, error_code, message):
        ''''''
        self._fail = True
        self.reason = error_code
        self._error = message
1310337
function handleError(error, ignoreError) {
    appStore.setLoading(false)
    let reason

    if (error.response) {
        reason = handleResponseError(error)
    } else if (error.status >= 200 && error.status < 300) {
        reason = handleServiceError(error)
    } else {
        reason = handleRequestError(error)
    }

    if (ignoreError !== true) {
        appStore.setError(reason)
    }

    return Promise.reject(reason)
}
69068
def handle_error(self, error, response):
        
        query_params = {"error": error.error}

        query = urlencode(query_params)

        location = "%s?%s" % (self.client.redirect_uri, query)

        response.status_code = 302
        response.body = ""
        response.add_header("Location", location)

        return response
447025
def consult_error_hook(self, item_session: ItemSession, error: BaseException):
        ''''''
        try:
            return self.hook_dispatcher.call(
                PluginFunctions.handle_error, item_session, error)
        except HookDisconnected:
            return Actions.NORMAL
789455
def _process_request(self, request, client_address):
        """"""
        try:
            self.finish_request(request, client_address)
        except Exception:
            self.handle_error(request, client_address)
        finally:
            self.shutdown_request(request)