If there is an unexpected status code, it gets the status message, closes
the response, and throws an exception.

@throws ClientException
507610
private void errorIf(ClientResponse response,
            ClientResponse.Status[] status, boolean bool)
            throws ClientException {
        ClientResponse.Status clientResponseStatus
                = response.getClientResponseStatus();
        if (bool) {
            if (contains(status, clientResponseStatus)) {
                String message = response.getEntity(String.class);
                throw new ClientException(clientResponseStatus, message);
            }
        } else if (!contains(status, clientResponseStatus)) {
            String message = response.getEntity(String.class);
            throw new ClientException(clientResponseStatus, message);
        }
    }
86696
async def _handle_exception(self, e, sock):
        
        if isinstance(e, (RemoteProtocolError, AssertionError)):
            await sock.close()
            raise BadHttpResponse('Invalid HTTP response from server.') from e

        if isinstance(e, Exception):
            await sock.close()
            raise e
822523
def jsonify_error(message_or_exception, status_code=400):
    """"""
    if isinstance(message_or_exception, Exception):
        message = '%s: %s' % (
            message_or_exception.__class__.__name__, message_or_exception)
    else:
        message = message_or_exception

    logging.debug('Returning status=%s, error message: %s',
                  status_code, message)
    response = jsonify(error=message)
    response.status_code = status_code
    return response
319955
@Override
	public void close() throws Exception {
		try {
			if (outputStream != null) {
				outputStream.flush();
				outputStream.close();
			}

			// first regular attempt to cleanly close. Failing that will escalate
			if (client != null) {
				client.close();
			}
		}
		catch (Exception e) {
			throw new IOException("Error while closing connection that streams data back to client at "
					+ hostIp.toString() + ":" + port, e);
		}
		finally {
			// if we failed prior to closing the client, close it
			if (client != null) {
				try {
					client.close();
				}
				catch (Throwable t) {
					// best effort to close, we do not care about an exception here any more
				}
			}
		}
	}
388713
public synchronized void waitForStart()
	throws ServerException,
	       ClientException,
	       IOException {
	    try {
	        while(!isStarted() && !hasError()) {
		        wait();
	        }
	    } catch(InterruptedException e) {
            // break
	    }
	    checkError();
    }
30717
public void init() throws Exception {

        // If the status file exists, make sure it doesn't indicate
        // that the server is running!
        if (_statusFile.exists()) {
            ServerStatusMessage[] messages = getAllMessages();
            ServerStatusMessage lastMessage = messages[messages.length - 1];
            if (lastMessage.getState() == ServerState.STARTED) {
                throw new Exception("The server is already running or was shut down unexpectedly.\n"
                        + "If the server has shut down unexpectedly, you must manually delete\n"
                        + "the following file: "
                        + _statusFile.getPath()
                        + "\n"
                        + "then try again.");
            }
        }

        _statusFile.clear();
        _statusFile.append(ServerState.NOT_STARTING,
                           "Waiting for startup to begin");
    }
507293
@Override
    protected HttpResponse onFailure(ServiceRequestContext ctx, HttpRequest req, @Nullable Throwable cause)
            throws Exception {
        return HttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE);
    }
59485
public boolean status(int responseCode) {
		if (urlConnection instanceof HttpURLConnection) {
			HttpURLConnection http = (HttpURLConnection) urlConnection;
			try {
				return http.getResponseCode() == responseCode;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		} else
			return false;
	}
1172953
@SuppressWarnings("unused")
    private void close() {
        try {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Doing client selector close");
            }
            selector.close();
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Closed client selector");
            }
        } catch (IOException e) {
            LOGGER.warn("Ignoring exception during selector close", e);
        }
    }
1230766
public void release() throws HttpException {
    try {
      HttpEntity ent = getResponseEntity();

      if (ent != null) {
        InputStream is = ent.getContent();
        is.close();
      }
    } catch (Throwable t) {
      throw new HttpException(t.getLocalizedMessage(), t);
    }
  }
337399
protected void checkClosed() throws JMSException {
        if (getState() == CLOSED) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(this, tc, "This Connection is closed.");
            throw (javax.jms.IllegalStateException) JmsErrorUtils.newThrowable(javax.jms.IllegalStateException.class,
                                                                               "CONNECTION_CLOSED_CWSIA0021",
                                                                               null, tc);
        }
    }
652710
protected Event handleException(final J2EContext webContext, final BaseClient<Credentials, CommonProfile> client, final Exception e) {
        if (e instanceof RequestSloException) {
            try {
                webContext.getResponse().sendRedirect("logout");
            } catch (final IOException ioe) {
                throw new IllegalArgumentException("Unable to call logout", ioe);
            }
            return stopWebflow();
        }
        val msg = String.format("Delegated authentication has failed with client %s", client.getName());
        LOGGER.error(msg, e);
        throw new IllegalArgumentException(msg);
    }
1110604
private boolean simulateHttpStatusCode(Message replyMessage) throws IOException {
        if (replyMessage == null || CollectionUtils.isEmpty(replyMessage.getHeaders())) {
            return false;
        }
        
        for (Entry<String, Object> headerEntry : replyMessage.getHeaders().entrySet()) {
            if (headerEntry.getKey().equalsIgnoreCase(SoapMessageHeaders.HTTP_STATUS_CODE)) {
                WebServiceConnection connection = TransportContextHolder.getTransportContext().getConnection();
                
                int statusCode = Integer.valueOf(headerEntry.getValue().toString());
                if (connection instanceof HttpServletConnection) {
                    ((HttpServletConnection)connection).setFault(false);
                    ((HttpServletConnection)connection).getHttpServletResponse().setStatus(statusCode);
                    return true;
                } else {
                    log.warn("Unable to set custom Http status code on connection other than HttpServletConnection (" + connection.getClass().getName() + ")");
                }
            }
        }
        
        return false;
    }
183525
public static boolean isClientAbortException(IOException e) {
		
		String exceptionClassName = e.getClass().getName();
		return exceptionClassName.endsWith(".EofException")
				|| exceptionClassName.endsWith(".ClientAbortException");
	}
1101007
@Override
  public void onTimeout()
  {
    try {
      //request().sendError(WebRequest.INTERNAL_SERVER_ERROR);
      if (true) throw new UnsupportedOperationException();
    } catch (Exception e) {
      log.log(Level.FINEST, e.toString(), e);
    }
    
    closeResponse();
  }
1285432
private void tryHandleException(HttpCallContext ctx,
	                                HttpServletResponse response,
	                                Throwable t) throws ServletException, IOException, RuntimeException, Error
	{
		if (suppressClientAbortExceptions && t instanceof UnhandledException && t.getCause() != null)
		{
			// Only look 20 exceptions deep
			int maxDepth = 20;
			Throwable cause = t.getCause();

			while (cause != null && --maxDepth > 0)
			{
				if (cause.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException"))
				{
					ignoredAborts.mark();

					if (log.isTraceEnabled())
						log.trace("Client aborted during request. Ignoring. Detail: " + ctx.getRequestInfo(), t);

					return;
				}
				else
				{
					cause = cause.getCause();
				}
			}
		}

		log.warn("Failure during " + ctx.getRequestInfo(), t);

		// If the response is already committed we can't render the exception elegantly
		if (response.isCommitted())
			rethrow(t);

		try
		{
			RestFailureMarshaller marshaller = new RestFailureMarshaller();
			RestFailure failure = marshaller.renderFailure(t);

			TwitterBootstrapRestFailurePageRenderer renderer = new TwitterBootstrapRestFailurePageRenderer(failure);

			response.setStatus(500); // internal error

			// Render the HTML
			final StringBuilder sb = new StringBuilder(4096);
			renderer.writeHTML(sb);

			response.getWriter().print(sb);
		}
		catch (Throwable newException)
		{
			log.warn("Error trying to present exception elegantly: ", newException);

			// Rethrow the original exception, it's not our problem anymore
			rethrow(t);
		}
	}
1022474
function onClientTimeoutPostRequestHandler (ctx, err) {
  if (err) {
    let error = null;
    if (err instanceof SuperError) {
      error = err.rootCause || err.cause || err;
    } else {
      error = err;
    }

    let internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR).causedBy(err);
    ctx.log.error(internalError);

    ctx._response.error = error;
    ctx.emit('clientResponseError', error);
  }

  try {
    ctx._execute(ctx._response.error);
  } catch(err) {
    let error = null;
    if (err instanceof SuperError) {
      error = err.rootCause || err.cause || err;
    } else {
      error = err;
    }

    let internalError = new Errors.FatalError(Constants.FATAL_ERROR, ctx.errorDetails).causedBy(err);
    ctx.log.fatal(internalError);

    ctx.emit('clientResponseError', error);

    // let it crash
    if (ctx._config.crashOnFatal) {
      ctx.fatal();
    }
  }
}