Dispatch incoming request and capture top level exceptions.
188819
def dispatch(self, operation, request, **path_args):
        
        # Add current operation to the request (for convenience in middleware methods)
        request.current_operation = operation

        try:
            for middleware in self.middleware.pre_request:
                response = middleware(request, path_args)
                # Return HttpResponse if one is returned.
                if isinstance(response, HttpResponse):
                    return response

            response = self._dispatch(operation, request, path_args)

            for middleware in self.middleware.post_request:
                response = middleware(request, response)

        except Exception as ex:
            if self.debug_enabled:
                # If debug is enabled then fallback to the frameworks default
                # error processing, this often provides convenience features
                # to aid in the debugging process.
                raise
            self.handle_500(request, ex)
            return HttpResponse("Error processing response.", HTTPStatus.INTERNAL_SERVER_ERROR)

        else:
            return response
1003421
def dispatch_hook(key, hooks, hook_data):
    """"""

    hooks = hooks or dict()

    if key in hooks:
        try:
            return hooks.get(key).__call__(hook_data) or hook_data

        except Exception, why:
            warnings.warn(str(why))

    return hook_data
71225
private function _dispatchRequest($request)
	{
		// track the number of requests across instances
		self::$requestCount++;
		$timestart = microtime(true);

		$response = self::transport()->send($request);

		// pass the response through the filter chain
		foreach($this->_filters as $filter)
		{
			$response = $filter->response($response);
		}

		$httpCode = $response->getStatus()->getCode();
		$location = $response->getHeaders()->value('Location');
		$body = $response->getBody();

		// track the time taken across instances
		self::$requestTime += microtime(true) - $timestart;

		// process a redirect if needed
		if($httpCode < 400 && $location)
		{
			return $this->_redirect($location);
		}
		else
		{
			$this->_redirects = 0;
		}

		// translate error code to a typed exception
		if($httpCode == 500)
		{
			throw new Error\InternalServerError($body);
		}
		elseif($httpCode == 400)
		{
			throw new Error\BadRequest($body);
		}
		elseif($httpCode == 401)
		{
			throw new Error\Unauthorized($body);
		}
		elseif($httpCode == 404)
		{
			throw new Error\NotFound($body);
		}
		else if($httpCode >= 300)
		{
			throw new Error($body,$httpCode);
		}

		return $response;
	}
1150791
def dispatch(self, request, **kwargs):
        '''
        
        '''

        # Check if this is a webservice request
        self.json_worker = (bool(getattr(self.request, "authtoken", False))) or (self.json is True)
        self.__authtoken = (bool(getattr(self.request, "authtoken", False)))

        # Check if this is an AJAX request
        if (request.is_ajax() or self.json_worker) and request.body:
            request.POST = QueryDict('').copy()
            body = request.body
            if type(request.body) == bytes:
                body = body.decode("utf-8")
            post = json.loads(body)
            for key in post:
                if type(post[key]) == dict and '__JSON_DATA__' in post[key]:
                    post[key] = json.dumps(post[key]['__JSON_DATA__'])

            request.POST.update(post)

        # Set class internal variables
        self._setup(request)

        # Call the base implementation
        return super(GenModify, self).dispatch(request, **kwargs)
375809
def process_action(*args)
      super
    rescue Exception => exception
      raise if RocketPants.pass_through_errors?
      # Otherwise, use the default built in handler.
      logger.error "Exception occured: #{exception.class.name} - #{exception.message}"
      logger.error "Exception backtrace:"
      exception.backtrace[0, 10].each do |backtrace_line|
        logger.error "=> #{backtrace_line}"
      end
      exception_notifier_callback.call(self, exception, request)
      render_error exception
    end
657279
def _do_dispatch(self, listeners, event_type, details):
        """"""
        possible_calls = len(listeners)
        call_failures = 0
        for listener in listeners:
            try:
                listener(event_type, details.copy())
            except Exception:
                self._logger.warn(
                    "Failure calling listener %s to notify about event"
                    " %s, details: %s", listener, event_type, details,
                    exc_info=True)
                call_failures += 1
        return _Notified(possible_calls,
                         possible_calls - call_failures,
                         call_failures)
47912
async def dispatch(self, request, view=None, **kwargs):
        """"""
        if view is None and request.method not in self.methods:
            raise HTTPMethodNotAllowed(request.method, self.methods)

        method = getattr(self, view or request.method.lower())
        response = await method(request, **kwargs)
        return await self.make_response(request, response)
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()
693647
def dispatch!
      invoke do
        static! if settings.static? && (request.get? || request.head?)
        filter! :before
        route!
      end
    rescue ::Exception => boom
      invoke { handle_exception!(boom) }
    ensure
      filter! :after unless env['sinatra.static_file']
    end
284992
def dispatch(self, request, *args, **kwargs):
        """"""
        self.request = DownstreamRequest(request)
        self.args = args
        self.kwargs = kwargs

        self._verify_config()

        self.middleware = MiddlewareSet(self.proxy_middleware)

        return self.proxy()
1310767
def dispatch_request(self, *args, **kwargs):
        
        self.args = args
        self.kwargs = kwargs
        self.meth = request.method.lower()
        self.resource = current_app.blueprints.get(request.blueprint, None)

        if not any([self.meth in self.methods, self.meth.upper() in self.methods]):
            return self.return_error(405)

        self.process_before_request_hooks()

        resp = super(Endpoint, self).dispatch_request(*args, **kwargs)
        resp = self.make_response(resp)

        resp = self.process_after_request_hooks(resp)

        return resp
996369
async def dispatch_websocket(
        self, websocket_context: Optional[WebsocketContext]=None,
    ) -> None:
        
        websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket
        if websocket_.routing_exception is not None:
            raise websocket_.routing_exception

        handler = self.view_functions[websocket_.url_rule.endpoint]
        return await handler(**websocket_.view_args)
695850
def dispatch_request(self, *args, **kwargs):
        """"""
        method = getattr(self, request.method.lower(), None)
        if method is None and request.method == 'HEAD':
            method = getattr(self, 'get', None)
        assert method is not None, 'Unimplemented method {}'.format(request.method)

        headers = {'Content-Type': 'application/vnd.api+json'}

        response = method(*args, **kwargs)

        if isinstance(response, Response):
            response.headers.add('Content-Type', 'application/vnd.api+json')
            return response

        if not isinstance(response, tuple):
            if isinstance(response, dict):
                response.update({'jsonapi': {'version': '1.0'}})
            return make_response(json.dumps(response, cls=JSONEncoder), 200, headers)

        try:
            data, status_code, headers = response
            headers.update({'Content-Type': 'application/vnd.api+json'})
        except ValueError:
            pass

        try:
            data, status_code = response
        except ValueError:
            pass

        if isinstance(data, dict):
            data.update({'jsonapi': {'version': '1.0'}})

        return make_response(json.dumps(data, cls=JSONEncoder), status_code, headers)
1026638
public void dispatchRequest(HttpRequest httpRequest) throws IOException {
		for (HttpRequestHandler handler : handlers) {
			HttpResponse resp = handler.handleRequest(httpRequest);
			if (resp != null) {
				httpRequest.getSession().sendResponse(resp);
				return;
			}
		}
		if (!hasCapability(HttpCapability.THREADEDRESPONSE)) {
			// If it's still here nothing handled it.
			httpRequest.getSession().sendResponse(new HttpResponse(HttpStatus.NOT_FOUND, HttpStatus.NOT_FOUND.toString()));
		}
	}
718675
function DispatchError(message) {
  Error.call(this);
  Error.captureStackTrace(this, arguments.callee);
  this.name = 'DispatchError';
  this.message = message;
}
419830
def catch_exceptions(orig_func):
    """"""

    @functools.wraps(orig_func)
    def catch_exceptions_wrapper(self, *args, **kwargs):
        try:
            return orig_func(self, *args, **kwargs)
        except arvados.errors.ApiError as e:
            logging.exception("Failure")
            return {"msg": e._get_reason(), "status_code": e.resp.status}, int(e.resp.status)
        except subprocess.CalledProcessError as e:
            return {"msg": str(e), "status_code": 500}, 500
        except MissingAuthorization:
            return {"msg": "'Authorization' header is missing or empty, expecting Arvados API token", "status_code": 401}, 401
        except ValueError as e:
            return {"msg": str(e), "status_code": 400}, 400
        except Exception as e:
            return {"msg": str(e), "status_code": 500}, 500

    return catch_exceptions_wrapper
613799
def dispatch(environ):
    '''
    
    '''
    method = environ['REQUEST_METHOD'].upper()

    if method == 'GET':
        return ("They found me. I don't know how, but they found me. "
                "Run for it, Marty!")
    elif method == 'POST':
        data = get_json(environ)
        return run_chunk(environ, data)
    else:
        raise HTTPError(405, 'Method Not Allowed')