All general exceptions thrown by services are caught here and translated into http conform responses with a status code {@code 500
Internal Server Error}.

@param ex The exception occurred
@return A response object wraps the server result
3825
@ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception ex) {
        EXC_LOGGER.error("[P] Presentation Layer Exception: " + ex.getLocalizedMessage(), ex);
        if (ex instanceof BehaviorAwareException) {
            BehaviorAwareException bae = (BehaviorAwareException) ex;
            return bae.toResponse(bae.getData());
        }
        if (ex instanceof BusinessRuntimeException) {
            BusinessRuntimeException bre = (BusinessRuntimeException) ex;
            return new ResponseEntity<>(Response.newBuilder()
                    .withMessage(bre.getMessage())
                    .withHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR.toString())
                    .withObj(new String[]{bre.getMessageKey()})
                    .build(),
                    HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
        if (ex instanceof HttpBusinessException) {
            HttpBusinessException e = (HttpBusinessException) ex;
            return new ResponseEntity<>(Response.newBuilder()
                    .withMessage(ex.getMessage())
                    .withHttpStatus(e.getHttpStatus().toString())
                    .build(),
                    e.getHttpStatus()
            );
        }
        if (ex instanceof ValidationException) {
            return new ResponseEntity<>(Response.newBuilder()
                    .withMessage(ex.getMessage())
                    .withHttpStatus(HttpStatus.BAD_REQUEST.toString())
                    .build(),
                    HttpStatus.BAD_REQUEST
            );
        }
        if (ex instanceof TechnicalRuntimeException) {
            return new ResponseEntity<>(Response.newBuilder()
                    .withMessage(ex.getMessage())
                    .withHttpStatus(HttpStatus.BAD_GATEWAY.toString())
                    .build(),
                    HttpStatus.BAD_GATEWAY
            );
        }
        return new ResponseEntity<>(Response.newBuilder()
                .withMessage(ex.getMessage())
                .withHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR.toString())
                .build(),
                HttpStatus.INTERNAL_SERVER_ERROR
        );
    }
681927
private function handleInternalException(\Exception $ex)
    {
        $response = null;

        if ($ex instanceof ResponseAwareExceptionInterface) {
            $response = $ex->getResponse();
        }

        if ($ex instanceof ServerStopExceptionInterface) {
            $this->stopServerByException($ex);
        }

        return $response;
    }
1337450
public static SQLException toSQLException(Throwable ex) {
        if (ex == null)
            return null; 

        if (ex instanceof SQLException)
            return (SQLException) ex;

        if (ex instanceof ResourceException)
            return toSQLException((ResourceException) ex);

        // Link the original exception to the new SQLException. 

        SQLException sqlX = new SQLException(ex.getClass().getName() + ": " + ex.getMessage());
        sqlX.initCause(ex);

        return sqlX;
    }
1304345
protected HyperionException readException(Response response) throws IOException
    {
        ErrorResponse errorResponse = null;
        try
        {
            errorResponse = objectMapper.readValue(response.body().byteStream(), ErrorResponse.class);
        }
        catch (Exception ignore)
        {
        }

        HyperionException resolvedException = null;
        if (errorResponse != null)
        {
            try
            {
                Class exceptionClass = Class.forName(errorResponse.getType());
                resolvedException = (HyperionException) exceptionClass.getConstructor(String.class)
                        .newInstance(errorResponse.getMessage());
            }
            catch (Throwable ignore)
            {
            }

            if (resolvedException == null)
            {
                resolvedException =
                        new HyperionException(errorResponse.getStatusCode(), errorResponse.getMessage());
            }

            resolvedException.setErrorDetails(errorResponse.getErrorDetails());
            resolvedException.setErrorTime(errorResponse.getErrorTime());
            resolvedException.setRequestId(errorResponse.getRequestId());
        }

        if (resolvedException == null)
        {
            resolvedException =
                    new HyperionException(response.code(), response.message());
        }

        return resolvedException;

    }
393446
public ResponseEntity<T> handleException(E ex, HttpServletRequest req) {

        logException(ex, req);

        T body = createBody(ex, req);
        HttpHeaders headers = createHeaders(ex, req);

        return new ResponseEntity<>(body, headers, getStatus());
    }
1153150
protected String excuteGet(String url, boolean useURI) throws Exception {
		HttpClient httpClient = getHttpClient();
		HttpUriRequest request = getGetRequest(url, useURI);
		
		HttpResponse httpResponse = httpClient.execute(request);

		String response = parseResponse(url, httpResponse);
		return response;
	}
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);
		}
	}
798553
public RuntimeException translate(String sql, List<Object> bindings, SQLException ex) {
        return exceptionTranslator.translate(sql, bindings, ex);
    }
474606
private boolean handleException(final Throwable t,
                                  final HttpServletResponse resp,
                                  final boolean serverError) {
    if (serverError) {
      return true;
    }

    try {
      error(t);
      sendError(t, resp);
      return true;
    } catch (Throwable t1) {
      // Pretty much screwed if we get here
      return true;
    }
  }
980455
public static boolean report(WsRuntimeFwException ex) {
        if (ex.reported) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "previously reported exception", new Exception(ex));
            }
            return false;
        }

        ex.reported = true;
        return true;
    }
60283
public static String convertExceptionToMessage(Throwable ex)
  {
    StringBuilder sb = new StringBuilder();
    if(ex != null)
    {
      sb.append("Exception type: ").append(ex.getClass().getName()).append("\n");
      sb.append("Message: ").append(ex.getLocalizedMessage()).append("\n");
      sb.append("Stacktrace: \n");
      StackTraceElement[] st = ex.getStackTrace();
      for (int i = 0; i < st.length; i++)
      {
        sb.append(st[i].toString());
        sb.append("\n");
      }
    }
    return sb.toString();
  }
640541
@ExceptionHandler(Exception.class)
    public ModelAndView handleUnauthorizedServiceException(final HttpServletRequest req, final Exception ex) {
        return WebUtils.produceUnauthorizedErrorView();
    }
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
143998
private void processExchange(final int idx, final HTTPExchange exch) {
        assertUnlocked();

        HTTPResponse resp;
        AbstractBody body;
        int respCode;
        try {
            if (LOG.isLoggable(Level.FINEST))
                LOG.finest(
                    "Thread " + idx + " is sending "
                        + exch.getRequest().getAttribute(Attributes.RID));

            resp = exch.getHTTPResponse();
            body = resp.getBody();
            respCode = resp.getHTTPStatus();

            if (LOG.isLoggable(Level.FINEST)) {
                String respRid = body.getAttribute(Attributes.RID);
                if (respRid == null)
                    respRid = exch.getRequest().getAttribute(Attributes.RID);
                LOG.finest(
                    "Thread " + idx + " received response"
                        + " for RID: " + respRid
                        + " code: " + respCode
                        + " ACK: " + body.getAttribute(Attributes.ACK));
            }
        } catch (BOSHException boshx) {
            LOG.log(Level.FINEST, "Could not obtain response", boshx);
            dispose(boshx);
            return;
        } catch (InterruptedException intx) {
            LOG.log(Level.FINEST, INTERRUPTED, intx);
            dispose(intx);
            return;
        }
        fireResponseReceived(body);

        // Process the message with the current session state
        AbstractBody req = exch.getRequest();
        CMSessionParams params;
        List<HTTPExchange> toResend = null;
        lock.lock();
        try {
            if (!isWorking()) {
                lock.unlock();
                return;
            }
            
            // Check for session creation response info, if needed
            if (cmParams == null) {
                cmParams = CMSessionParams.fromSessionInit(req, body);

                // Adjust number of request processors based on REQ value
                adjustRequestProcessorsPool();

                // The following call handles the lock. It's not an escape.
                fireConnectionEstablished();
            }
            params = cmParams;

            checkForTerminalBindingConditions(body, respCode);
            if (isTermination(body)) {
                // Explicit termination
                lock.unlock();
                dispose(null);
                return;
            }

            // FIXME this may not work with more than 1 RequestProcessor
            if (isRecoverableBindingCondition(body)) {
                // Retransmit outstanding requests
                if (toResend == null) {
                    toResend = new ArrayList<HTTPExchange>(exchanges.size());
                }
                for (HTTPExchange exchange : exchanges) {
                    HTTPExchange resendExch =
                            new HTTPExchange(exchange.getRequest());
                    toResend.add(resendExch);
                }
                for (HTTPExchange exchange : toResend) {
                    exchanges.add(exchange);
                }
            } else {
                // Process message as normal
                processRequestAcknowledgements(req, body);
                processResponseAcknowledgementData(req);
                HTTPExchange resendExch =
                        processResponseAcknowledgementReport(body);
                if (resendExch != null && toResend == null) {
                    toResend = new ArrayList<HTTPExchange>(1);
                    toResend.add(resendExch);
                    exchanges.add(resendExch);
                }
            }
        } catch (BOSHException boshx) {
            LOG.log(Level.FINEST, "Could not process response", boshx);
            lock.unlock();
            dispose(boshx);
            return;
        } finally {
            if (lock.isHeldByCurrentThread()) {
                try {
                    exchanges.remove(exch);
                    if (exchanges.isEmpty()) {
                        scheduleEmptyRequest(processPauseRequest(req));
                    }
                    notFull.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        }

        if (toResend != null) {
            for (HTTPExchange resend : toResend) {
                HTTPResponse response =
                        httpSender.send(params, resend.getRequest());
                resend.setHTTPResponse(response);
                fireRequestSent(resend.getRequest());
            }
        }
    }
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);
	}
479263
private void exception(Throwable e)
    {
        try
        {
            _persistent=false;
            int error_code=HttpResponse.__500_Internal_Server_Error;
            
            if (e instanceof HttpException)
            {
                error_code=((HttpException)e).getCode();
                
                if (_request==null)
                    log.warn(e.toString());
                else
                    log.warn(_request.getRequestLine()+" "+e.toString());
                log.debug(LogSupport.EXCEPTION,e);
            }
            else if (e instanceof EOFException)
            {
                LogSupport.ignore(log,e);
                return;
            }
            else
            {
                _request.setAttribute("javax.servlet.error.exception_type",e.getClass());
                _request.setAttribute("javax.servlet.error.exception",e);
                
                if (_request==null)
                    log.warn(LogSupport.EXCEPTION,e);
                else
                    log.warn(_request.getRequestLine(),e);
            }
            
            if (_response != null && !_response.isCommitted())
            {
                _response.reset();
                _response.removeField(HttpFields.__TransferEncoding);
                _response.setField(HttpFields.__Connection,HttpFields.__Close);
                _response.sendError(error_code);
            }
        }
        catch(Exception ex)
        {
            LogSupport.ignore(log,ex);
        }
    }
1011547
public Response createErrorResponse(String req, Map<String,String> metaInfo, ServiceException ex) {
        Request request = new Request(0L);
        request.setContent(req);

        Response response = new Response();
        String contentType = metaInfo.get(Listener.METAINFO_CONTENT_TYPE);
        if (contentType == null && req != null && !req.isEmpty())
            contentType = req.trim().startsWith("{") ? Listener.CONTENT_TYPE_JSON : Listener.CONTENT_TYPE_XML;
        if (contentType == null)
            contentType = Listener.CONTENT_TYPE_XML; // compatibility

        metaInfo.put(Listener.METAINFO_HTTP_STATUS_CODE, String.valueOf(ex.getCode()));

        StatusMessage statusMsg = new StatusMessage();
        statusMsg.setCode(ex.getCode());
        statusMsg.setMessage(ex.getMessage());
        response.setStatusCode(statusMsg.getCode());
        response.setStatusMessage(statusMsg.getMessage());
        response.setPath(ServicePaths.getInboundResponsePath(metaInfo));
        if (contentType.equals(Listener.CONTENT_TYPE_JSON)) {
            response.setContent(statusMsg.getJsonString());
        }
        else {
            response.setContent(statusMsg.getXml());
        }
        return response;
    }