Send info about thrown exception and set proper HTTP code.
196749
public static function sendException(\Exception $ex)
	{
		$class = get_class($ex);
		switch ($class) {
			case 'Smalldb\\StateMachine\\TransitionAccessException':
				$http_code = '403';
				break;
			case 'Smalldb\\StateMachine\\InstanceDoesNotExistException':
				$http_code = '404';
				break;
			default:
				$http_code = '500';
				break;
		}

		header("HTTP/1.0 $http_code Exception: $class");
		header('Content-Type: application/json; encoding=utf-8');
		static::writeException($ex);
	}
416368
def process_exception(self, request, exception):
        
        if isinstance(exception, HttpRedirectRequest):
            return HttpResponseRedirect(exception.url, status=exception.status)
        else:
            return None
380390
def http_exception(channel, title):
    

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Too much help",
        "{} is too helpful! Try trimming some of the help messages.".format(title),
        modulename=modulename
    )

    return gui
249504
def process_exception(self, request, e):
        
        if isinstance(e, RedirectException):
            response = e.get_response()
            self.process_response(request, response)
841711
def send_http_error(self, http_code, cim_error=None,
                        cim_error_details=None, headers=None):
        
        self.send_response(http_code, http_client.responses.get(http_code, ''))
        self.send_header("CIMExport", "MethodResponse")
        if cim_error is not None:
            self.send_header("CIMError", cim_error)
        if cim_error_details is not None:
            self.send_header("CIMErrorDetails", cim_error_details)
        if headers is not None:
            for header, value in headers:
                self.send_header(header, value)
        self.end_headers()
        self.log('%s: HTTP status %s; CIMError: %s, CIMErrorDetails: %s',
                 (self._get_log_prefix(), http_code, cim_error,
                  cim_error_details),
                 logging.WARNING)
1076710
def write_error(self, status_code, **kwargs):
        
        http_error = _get_http_error(kwargs)
        if http_error:
            self.finish(self._error_template(status_code,
                                             http_error.errors,
                                             http_error.source))
        else:
            source = kwargs.get('source', getattr(options, 'name', None))
            # Slightly annoyed that have to rely on the internal self._reason
            # to deal with unhandled exceptions. On the dev version of
            # tornado self._reason is always set, while in the current version
            # a reason kwarg is passed down from `send_error` but not set
            # on the instance.
            reason = kwargs.get('reason', self._reason)
            self.finish(self._error_template(status_code, reason, source))
1257649
def throw_if_bad_response(response):
    """"""
    try:
        response.raise_for_status()
    except RequestException:
        try:
            msg = 'Response code: {}; response body:\n{}'.format(response.status_code, json.dumps(response.json(), indent=2))
            raise CerberusClientException(msg)
        except ValueError:
            msg = 'Response code: {}; response body:\n{}'.format(response.status_code, response.text)
            raise CerberusClientException(msg)
194772
def set_exception(self, exception):
        """"""
        was_handled = self._finish(self.errbacks, exception)
        if not was_handled:
            traceback.print_exception(
                type(exception), exception, exception.__traceback__)
934817
public function sendResponse()
    {
        $this->sendHeaders();

        if ($this->isException() && $this->renderExceptions())
        {
            $exceptions = '';
            foreach ($this->getException() as $e)
            {
                $exceptions .= $e->__toString() . "\n";
            }
            echo $exceptions;
            return;
        }

        $this->outputBody();
    }
94739
public void sendError(int status, String message)
        throws IOException
    {
        // Find  error page.
        String error_page =
            _servletHttpRequest.getServletHandler().getErrorPage(status,_servletHttpRequest);

        resetBuffer();
        
        // Handle error page?
        if (error_page==null)
        {
            // handle normally
            _httpResponse.sendError(status,message);
        }
        else
        {   
            _httpResponse.setStatus(status,message);
            
            if (message == null)
            {
                message= (String)HttpResponse.__statusMsg.get(TypeUtil.newInteger(status));
                if (message == null)
                    message= "" + status;
            }

            // handle error page
            ServletHolder holder = _servletHttpRequest.getServletHolder();
            if (holder!=null)
                _servletHttpRequest.setAttribute(ServletHandler.__J_S_ERROR_SERVLET_NAME,
                                                 holder.getName());
            _servletHttpRequest.setAttribute(ServletHandler.__J_S_ERROR_REQUEST_URI,
                                             _servletHttpRequest.getRequestURI());
            _servletHttpRequest.setAttribute(ServletHandler.__J_S_ERROR_STATUS_CODE,
                                             new Integer(status));
            _servletHttpRequest.setAttribute(ServletHandler.__J_S_ERROR_MESSAGE,
                                             message);
            
            RequestDispatcher dispatcher=
                _servletHttpRequest.getServletHandler().getServletContext()
                .getRequestDispatcher(error_page);

            try
            {
                ((Dispatcher)dispatcher).error(_servletHttpRequest,this);
            }
            catch(ServletException e)
            {
                log.warn(LogSupport.EXCEPTION,e);
                _httpResponse.sendError(status,message); 
            }
        }
        complete();
    }
819482
def write_error(self, status_code, **kwargs):
        
        reason = self._reason

        if self.settings.get("serve_traceback") and "exc_info" in kwargs:
            error = []
            for line in traceback.format_exception(*kwargs["exc_info"]):
                error.append(line)
        else:
            error = None
        data = {'_traceback': error, 'message': reason, 'code': status_code}
        content = self.render_exception(**data)
        self.write(content)
616955
def error_response(self, code, content=''):
        """"""
        self.send_response(code)
        self.send_header('Content-Type', 'text/xml')
        self.add_compliance_header()
        self.end_headers()
        self.wfile.write(content)
1333325
private void sendRequest(HttpUriRequest request, int expectedStatus)
      throws Exception {
    addAuthHeader(request);
    
    HttpClient client = httpClient();
    
    HttpResponse response = client.execute(request);
    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
      EntityUtils.consume(response.getEntity());
      System.err.println("Authentication has been disabled for "+args.get(1)+".");
    } else if(response.getStatusLine().getStatusCode() == expectedStatus) {
      if(expectedStatus == HttpStatus.SC_OK) {
        String responseStr = EntityUtils.toString(response.getEntity());
        List<String> usernames = new Gson().fromJson(responseStr, new TypeToken<List<String>>(){}.getType());
        if(usernames == null || usernames.isEmpty()) {
          System.out.println("There have been no site specific users created.");
        } else {
          System.out.println(usernames.size() + " Users:");
          for(String user : usernames) {
            System.out.println(user);
          }
        }
      }
    } else {
      System.err.println(EntityUtils.toString(response.getEntity()));
      System.err.println("Unexpected status code returned. "+response.getStatusLine().getStatusCode());
    }
  }
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
1181215
protected function handleException(\Exception $exception, $httpCode)
    {
        $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']);

        if ($isAjax) {
            $sEngine = Response\Factory::ENGINE_API;
            $sFormat = Response\Factory::FORMAT_JSON;
            $content = json_encode($exception->getTraceAsString());
        } else {
            $sEngine = Response\Factory::ENGINE_NONE;
            $sFormat = Response\Factory::FORMAT_HTML;
            $content = '<b>Exception[' . $exception->getCode() . ']: ' . $exception->getMessage() . '</b>
            <pre>' . $exception->getTraceAsString() . '</pre>';
        }

        $response = Response\Factory::create($sFormat, $sEngine);
        $response->setHttpCode($httpCode)
            ->setContent($content)
            ->send();
    }
1317394
def _raise_for_status(response):
    '''
    
    '''
    http_error_msg = ""

    if 400 <= response.status_code < 500:
        http_error_msg = "{0} Client Error: {1}".format(response.status_code,
                                                        response.reason)

    elif 500 <= response.status_code < 600:
        http_error_msg = "{0} Server Error: {1}".format(response.status_code,
                                                        response.reason)

    if http_error_msg:
        try:
            more_info = response.json().get("message")
        except ValueError:
            more_info = None
        if more_info and more_info.lower() != response.reason.lower():
            http_error_msg += ".\n\t{0}".format(more_info)
        raise requests.exceptions.HTTPError(http_error_msg, response=response)
877996
public function Send () {
		if ($this->IsSent()) return;
		$httpVersion = $this->GetHttpVersion();
		$code = $this->GetCode();
		$status = $this->codeMessage !== NULL
			? ' '.$this->codeMessage
			: (isset(static::$codeMessages[$code]) 
				? ' '.static::$codeMessages[$code] 
				: '');
		if (!isset($this->headers['Content-Encoding'])) {
			if (!$this->encoding) $this->encoding = 'utf-8';
			$this->headers['Content-Encoding'] = $this->encoding;
		}
		$this->UpdateHeaders();
		header($httpVersion . ' ' . $code . $status);
		header('Host: ' . $this->request->GetHost());
		foreach ($this->headers as $name => $value) {
			if ($name == 'Content-Type') {
				$charsetMatched = FALSE;
				$charsetPos = strpos($value, 'charset');
				if ($charsetPos !== FALSE) {
					$equalPos = strpos($value, '=', $charsetPos);
					if ($equalPos !== FALSE) $charsetMatched = TRUE;
				}
				if (!$charsetMatched) $value .= ';charset=' . $this->encoding;
			}
			if (isset($this->disabledHeaders[$name])) {
				header_remove($name);
			} else {
				header($name . ": " . $value);
			}
		}
		foreach ($this->disabledHeaders as $name => $b)
			header_remove($name);
		$this->addTimeAndMemoryHeader();
		echo $this->body;
		if (ob_get_level()) echo ob_get_clean();
		flush();
		$this->sent = TRUE;
	}