Render exceptions. Adds error messages and the stack trace to the json model
and sets the response status accordingly to note bad requests.

@param ex       the ex
@param response the response
343172
public static void renderException(final Exception ex, final HttpServletResponse response) {
        val map = new HashMap<String, String>();
        map.put("error", ex.getMessage());
        map.put("stacktrace", Arrays.deepToString(ex.getStackTrace()));
        renderException(map, response);
    }
1230396
function Request__render(response) {

        if (this.isRendered) {
            return false;
        }



        if (Type.isString(response)) {
            this._checkContentType('text/html');
            this.response.writeHead(this.statusCode, this.headers);

            this.addHeader('Content-Length', response.length);
            this.response.end(response);
            this.isRendered = true;
            logger.info('Request.render:', {
                url: this.url,
                status: this.statusCode,
                id: this.id,
                isRendered: this.isRendered,
                content_type: this.getHeader('content-type')
            });
            return true;
        } else if (response instanceof Buffer) {
            this._checkContentType('text/html');
            this.response.writeHead(this.statusCode, this.headers);
            this.addHeader('Content-Length', response.length);
            this.response.end(response);
            this.isRendered = true;
            logger.info('Request.render:', {
                url: this.url,
                status: this.statusCode,
                id: this.id,
                isRendered: this.isRendered,
                content_type: this.getHeader('content-type')
            });
            return true;
        } else if (!response) {
            logger.error('Request.error:', {
                url: this.url,
                status: this.statusCode,
                id: this.id,
                response: response,
                isRendered: this.isRendered,
                content_type: this.getHeader('content-type'),
                message: 'No data to render'
            });
            throw new error.HttpError(500, {}, 'No data to render');
        } else {
            logger.error('Request.error:', {
                url: this.url,
                status: this.statusCode,
                id: this.id,
                response: response,
                isRendered: this.isRendered,
                content_type: this.getHeader('content-type'),
                message: 'Invalid response type'
            });
            throw new error.HttpError(500, {}, 'Invalid response type, string or buffer is required!');
        }
    }
640541
@ExceptionHandler(Exception.class)
    public ModelAndView handleUnauthorizedServiceException(final HttpServletRequest req, final Exception ex) {
        return WebUtils.produceUnauthorizedErrorView();
    }
259260
public static function writeException(\Exception $ex)
	{
		$response = array(
			'exception' => get_class($ex),
			'message' => $ex->getMessage(),
			'code' => $ex->getCode(),
		);
		static::writeJson($response);
	}
455596
@Override
	public void render() {
		try {
			final HttpServletRequest request = Request.getServletRequest();
			request.getRequestDispatcher(uri).forward(request, Response.getServletResponse());
		} catch (Exception e) {
			throw new RenderException("Forward to " + uri + " error!", e);
		}
	}
134386
public function render($request, $e)
	{
		if ($e instanceof \Error)
		{
			$e = new \Exception('Exception occured: ' . $e->getMessage() . "\nOriginal stack trace: " . 
				$e->getTraceAsString(), $e->getCode());
		}
		
		// If the request wants JSON (AJAX doesn't always want JSON)
		if ($request->wantsJson())
		{
			// Define the response
			$response = [
				'errors' => 'Sorry, something went wrong.'
			];

			// If the app is in debug mode
			if (config('app.debug'))
			{
				// Add the exception class name, message and stack trace to response
				$response['exception'] = get_class($e); // Reflection might be better here
				$response['message'] = $e->getMessage();
				$response['trace'] = $e->getTrace();
			}

			// Default response of 400
			$status = 400;

			// If this exception is an instance of HttpException
			if ($this->isHttpException($e))
			{
				// Grab the HTTP status code from the Exception
				$status = $e->getStatusCode();
			}

			// Return a JSON response with the response array and status code
			return response()->json($response, $status);
		}
		
		if ($this->isHttpException($e))
		{
			return $this->renderHttpException($e);
		}
		else
		{
			return (new SymfonyDisplayer(config('app.debug')))->createResponse($e);
		}
	}
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);
		}
	}
605336
private function displayError(Request $request,Response $response){
        $exception=$response->getContent();

        $data=array(
            'statusCode'=>$response->getStatusCode()
        ,'message'=>$exception->getMessage()
        ,'exception'=>get_class($exception)
        ,'file'=>$exception->getFile()
        ,'line'=>$exception->getLine()
        );

        if($this->environment->isDebug()){
            echo $this->twig->render('error.twig', $data);
        }
        else{
            echo $this->twig->render($response->getStatusCode().'.twig');
        }
    }
866070
@Override
  public void internalError(final Exception cause) {
    logError("Internal Server Error on " + request().getUri(), cause);

    if (this.api_version > 0) {
      // always default to the latest version of the error formatter since we
      // need to return something
      switch (this.api_version) {
        case 1:
        default:
          sendReply(HttpResponseStatus.INTERNAL_SERVER_ERROR,
              serializer.formatErrorV1(cause));
      }
      return;
    }

    ThrowableProxy tp = new ThrowableProxy(cause);
    tp.calculatePackagingData();
    final String pretty_exc = ThrowableProxyUtil.asString(tp);
    tp = null;
    if (hasQueryStringParam("json")) {
      // 32 = 10 + some extra space as exceptions always have \t's to escape.
      final StringBuilder buf = new StringBuilder(32 + pretty_exc.length());
      buf.append("{\"err\":\"");
      HttpQuery.escapeJson(pretty_exc, buf);
      buf.append("\"}");
      sendReply(HttpResponseStatus.INTERNAL_SERVER_ERROR, buf);
    } else {
      sendReply(HttpResponseStatus.INTERNAL_SERVER_ERROR,
                makePage("Internal Server Error", "Houston, we have a problem",
                         "<blockquote>"
                         + "<h1>Internal Server Error</h1>"
                         + "Oops, sorry but your request failed due to a"
                         + " server error.<br/><br/>"
                         + "Please try again in 30 seconds.<pre>"
                         + pretty_exc
                         + "</pre></blockquote>"));
    }
  }
730689
function apiError(response, error) {
  var content = errorContentExt(ErrorType.server, error);
  send(response, content, StatusCode.internalServerError);
}
456239
private void responseErrorToClient(Exception ex, User user) {
	    BadRequestException e = getBadRequestException(ex);
	    if(!e.isSendToClient())    return;
	    ISFSObject params = new SFSObject();
	    params.putUtfString(APIKey.MESSAGE, e.getReason());
	    params.putInt(APIKey.CODE, e.getCode());
	    send(APIKey.ERROR, params, user);
	}
45297
public static function render($file, $ex) : void
    {
        if (php_sapi_name() === 'cli') {
            exit(json_encode($ex));
        }

        http_response_code(500);
        require ouch_views($file);
        exit(1); //stop execution on first error
    }
958576
protected void sendError( String errText, HttpServletResponse response )
        throws IOException
    {
        sendError( errText, null, response );
    }
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
        );
    }
182602
public static boolean handleCommonError(Throwable ex, String action)
  {
    if(ex != null)
    {
      Throwable rootCause = ex;
      while(rootCause.getCause() != null)
      {
        rootCause = rootCause.getCause();
      }

      if(rootCause instanceof UniformInterfaceException)
      {
        UniformInterfaceException uniEx = (UniformInterfaceException) rootCause;
        
        if(uniEx.getResponse() != null)
        {
          if(uniEx.getResponse().getStatus() == 503)
          {
            // database connection error
            Notification n = new Notification(
                "Can't execute " + (action == null ? "" : "\"" + action + "\"" ) 
                + " action because database server is not responding.<br/>"
                + "There might be too many users using this service right now.", 
                Notification.Type.WARNING_MESSAGE);
            n.setDescription("<p><strong>Please try again later.</strong> If the error persists inform the administrator of this server.</p>"
                + "<p>Click on this message to close it.</p>"
                + "<p style=\"font-size:9pt;color:gray;\">Pinguin picture by Polar Cruises [CC BY 2.0 (http://creativecommons.org/licenses/by/2.0)], via Wikimedia Commons</p>");
            n.setIcon(PINGUIN_IMAGE);
            n.setHtmlContentAllowed(true);
            n.setDelayMsec(15000);
           
            n.show(Page.getCurrent());
            
            return true;
          }
        }
       
      }
    }
    return false;
  }
1319330
public void setResponse(JsonRpcResponse response) {
    if (response.isError()) {
      setException(response.error());
      return;
    }

    try {
      set((V) Messages.fromJson(method.outputBuilder(), response.result()));
    } catch (Exception e) {
      setException(e);
    }
  }
197570
def send_exception(self, response):
        
        # Get a formatted stack trace
        stack = traceback.format_exc()

        # Log the error
        self.log_error(
            "Error handling request upon: %s\n%s\n", self.path, stack
        )

        # Send the page
        response.send_content(
            500, self._service.make_exception_page(self.path, stack)
        )