Verbose exception handler
Sends HTML message with file where error occurred and stack trace

@param \Exception $exception
431779
public function handlerVerbose(\Exception $exception)
    {
        if (!headers_sent()) {
            header('HTTP/1.1 500 Internal Server Error', true, 500);
            header('Content-type: text/html; charset=UTF-8');
        }

        echo sprintf(
            '<!DOCTYPE html>
        <html>
        <head>
            <title>Bad Moss: %1$s - %2$s - %3$s:%4$u</title>
            <style>
                body, code { font: medium/1.5em monospace; }

                div:nth-child(4) { position: fixed; right: 0.5em; top: 0.5em; width: 100%; padding: 0.25em 1em; }
                div:nth-child(4) a { text-decoration: none; padding: 0.25em 0.75em; color: #ffe; background: #8c3; border-radius: 1em; }

                table { width: auto; border-collapse: collapse; overflow: hidden; }

                td { vertical-align: top; }
                td:nth-child(1) { position: relative; width: 3em; padding: 0 0.5em 0 0; text-align: right; color: #999; border-right: 1px solid #999; z-index: 1; }
                td:nth-child(2) { position: relative; padding: 0 0 0 0.5em; z-index: 2; }

                td, td span { white-space: nowrap; }
                td span#mark { position: relative; font-weight: bold; color: #f00; }
                td span#mark:after { content: \'.\'; position: absolute; top: -0.2em; left: -2em; width: 10000em; background: #f00; opacity: 0.25; }
            </style>
        </head>
        <body>
            <h1>Bad Moss: %1$s - &quot;%2$s&quot;</h1>

                <div>
                    <h2 id="trace">Trace</h2>
                    %6$s
                </div>
                <div>
                    <h2 id="listing">File: %3$s:%4$u</h2>
                    %5$s
                </div>
                <div>
                    <a href="#trace">Trace</a>
                    <a href="#listing">Listing</a>
                    <a href="#mark">Error line</a>
                </div>
        </body>
        </html>',
            get_class($exception),
            $exception->getMessage(),
            $exception->getFile(),
            $exception->getLine(),
            $this->lineNumbers('<br />', highlight_file($exception->getFile(), true), $exception->getLine()),
            $this->prettyCode($exception->getTrace())
        );
    }
1254212
public static function handleException(\Exception $exception) {
        $context = [];
        $second  = null;

        try {
            $context['class'    ] = __CLASS__;
            $context['file'     ] = $exception->getFile();  // If the location is not preset the logger will resolve the
            $context['line'     ] = $exception->getLine();  // exception handler as the originating location.
            $context['unhandled'] = true;

            Logger::log($exception, L_FATAL, $context);     // log with the highest level
        }

        // Exceptions thrown from within the exception handler will not be passed back to the handler again. Instead the
        // script terminates with an uncatchable fatal error.
        catch (\Exception $second) {
            $indent = ' ';                                  // the application is crashing, last try to log

            // secondary exception
            $msg2  = '[FATAL] Unhandled '.trim(DebugHelper::composeBetterMessage($second)).NL;
            $file  = $second->getFile();
            $line  = $second->getLine();
            $msg2 .= $indent.'in '.$file.' on line '.$line.NL.NL;
            $msg2 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL;
            $msg2 .= DebugHelper::getBetterTraceAsString($second, $indent);

            // primary (the causing) exception
            if (isset($context['cliMessage'])) {
                $msg1 = $context['cliMessage'];
                if (isset($context['cliExtra']))
                    $msg1 .= $context['cliExtra'];
            }
            else {
                $msg1  = $indent.'Unhandled '.trim(DebugHelper::composeBetterMessage($exception)).NL;
                $file  = $exception->getFile();
                $line  = $exception->getLine();
                $msg1 .= $indent.'in '.$file.' on line '.$line.NL.NL;
                $msg1 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL;
                $msg1 .= DebugHelper::getBetterTraceAsString($exception, $indent);
            }

            $msg  = $msg2.NL;
            $msg .= $indent.'caused by'.NL;
            $msg .= $msg1;
            $msg  = str_replace(chr(0), '?', $msg);         // replace NUL bytes which mess up the logfile

            if (CLI)                                        // full second exception
                echo $msg.NL;
            error_log(trim($msg), ERROR_LOG_DEFAULT);
        }

        // web: prevent an empty page
        if (!CLI) {
            try {
                if (Application::isAdminIP() || ini_get_bool('display_errors')) {
                    if ($second) {                          // full second exception, full log location
                        echoPre($second);
                        echoPre('error log: '.(strlen($errorLog=ini_get('error_log')) ? $errorLog : 'web server'));
                    }
                }
                else echoPre('application error (see error log)');
            }
            catch (\Exception $third) {
                echoPre('application error (see error log)');
            }
        }
    }
389014
public static function convertExceptionToString($exception)
    {
        if ($exception instanceof \Exception) {
            $message = "Exception ({$exception->getTraceAsString()})";
        } elseif ($exception instanceof \ErrorException) {
            $message = "{$exception->getTraceAsString()}";
        } else {
            $message = 'Exception';
        }
        $message .= " '".get_class($exception)."' with message '{$exception->getMessage()}' \n\nin "
            .$exception->getFile().':'.$exception->getLine()."\n\n"
            ."Stack trace:\n".$exception->getTraceAsString();

        return $message;
    }
1078728
public function wrapAndHandleException($exception)
    {
        if ($exception instanceof Error) {
            $exception = new Exception($exception);
        }

        $this->handleException($exception);
    }
612050
public function convertExceptionToHtml($exception)
    {
        $flat = $this->getFlattenedException($exception);

        $handler = new SymfonyExceptionHandler();

        return $this->decorate($handler->getContent($flat), $handler->getStylesheet($flat), $flat);
    }
1247108
public function catchException($exception)
    {
        if (in_array(get_class($exception), $this->config->getExcludeExceptions())) {
            return;
        }

        try {
            $this->send(
                Formatter::make($exception, $this->config)->toArray()
            );
        } catch (Exception $exception) {
            error_log('AfterBug Error: Couldn\'t notify. '.$exception->getMessage());
        }
    }
179186
public function handleException($exception)
    {
        if ($exception instanceof ExitException) {
            return;
        }

        $this->exception = $exception;

        // disable error capturing to avoid recursive errors while handling exceptions
        $this->unregister();

        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
        // HTTP exceptions will override this value in renderException()
        if (PHP_SAPI !== 'cli') {
            http_response_code(500);
        }

        try {
            $this->logException($exception);
            if ($this->discardExistingOutput) {
                $this->clearOutput();
            }
            $this->renderException($exception);
            if (!YII_ENV_TEST) {
                \Yii::getLogger()->flush(true);
                if (defined('HHVM_VERSION')) {
                    flush();
                }
                exit(1);
            }
        } catch (\Exception $e) {
            // an other exception could be thrown while displaying the exception
            $msg = "An Error occurred while handling another error:\n";
            $msg .= (string) $e;
            $msg .= "\nPrevious exception:\n";
            $msg .= (string) $exception;
            if (YII_DEBUG) {
                if (PHP_SAPI === 'cli') {
                    echo $msg . "\n";
                } else {
                    echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
                }
            } else {
                echo 'An internal server error occurred.';
            }
            $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
            error_log($msg);
            if (defined('HHVM_VERSION')) {
                flush();
            }
            exit(1);
        }

        $this->exception = null;
    }
1201514
protected function handle($exception)
  {
    Output::error($exception);

    if ($this->isAjax()) {
      $this->toJson($exception);
      return;
    }

    $this->toHtml($exception);
  }
1303023
public function renderException($exception)
	{
		if (!$this->getOption('v', 0))
		{
			$this->out('')->out($exception->getMessage());

			return;
		}

		parent::renderException($exception);
	}
254226
public function handleException(Exception &$exception)
    {
        if($template = end($this->_stack))
        {
            if($this->_source == $exception->getFile())
            {
                //Prevents any partial templates from leaking.
                ob_get_clean();

                //Re-create the exception and set the real file path
                if($exception instanceof ErrorException)
                {
                    $class = get_class($exception);
                    $file  = $this->getObject('template.locator.factory')->locate($template) ?: $this->_source;

                    $exception = new KTemplateExceptionError(
                        $exception->getMessage(),
                        $exception->getCode(),
                        $exception->getSeverity(),
                        $file,
                        $exception->getLine(),
                        $exception
                    );
                }
            }
        }
    }
687659
private function _handleException(Exception $exception)
    {
        $status = $exception->getCode();
        $statusText = \Slim\Http\Response::getMessageForCode($status);

        if ($statusText === null) {
            $status = 500;
            $statusText = 'Internal Server Error';
        }

        //Get app environment variables
        $env = $this->app->environment;

        $this->app->response->setStatus($status);

        if (isset($env['auth.JSONerrors']) && $env['auth.JSONerrors'] == true) {
            $this->app->response->headers->set('Content-Type', 'application/json');
            $this->app->response->setBody(
                json_encode(
                    [
                        'status' => ($status < 500) ? 'fail' : 'error',
                        'data' => [
                            'status' => $status,
                            'statusText' => preg_replace('/^[0-9]+ (.*)$/', '$1', $statusText),
                            'description' => $exception->getMessage(),
                        ],
                    ]
                )
            );
        } else {
            $this->app->response->setBody('<h1>'.$statusText.'</h1><h4>'.$exception->getMessage().'</h4>');
        }

        $this->app->response()->finalize();

        return $this->app->response();
    }
128762
public function errorhandler($exception) {
		$errstr		= $exception->getMessage();
		$errcode	= $exception->getCode();
		$backtrace	= $exception->getTrace();
		
		// the same should not be outputted more than once
		if ($errstr == $this->lasterror) return;
		$this->lasterror = $errstr;

		// count errors to produce unique ids
		$this->errorcounter++;

		// if it is an error throw away the first backtrace item
		if ($exception instanceof ErrorException) array_shift($backtrace);
		
		// add actual error to backtrace
		$bt['file'] = $exception->getFile();
		$bt['line'] = $exception->getLine();
		array_unshift($backtrace, $bt);
		
		// clean array
		$backtrace_keys = ['file'=>'', 'line'=>'', 'class'=>'', 'object'=>'', 'type'=>'', 'function'=>'', 'args'=>[]];
		foreach ($backtrace as $key => $value) {
			$backtrace[$key] = array_merge($backtrace_keys, $value);
		}
		
		// set the error code string
		if ($exception instanceof ErrorException) $errordescription = $this->errortypes[ $exception->getSeverity() ];
		elseif ($errcode == 0) $errordescription = 'EXCEPTION';
		else $errordescription = 'EXCEPTION (Code '.$errcode.')';

		// show error on screen
		if (!is_int($this->config['output']['screen'])) {
			die(__CLASS__ . ': debug.output.screen has to a valid PHP timestamp.');
		}

		if (time() < $this->config['output']['screen']) {
			$error = $this->_errorhandler_output($errstr, $backtrace, $errordescription);
			echo $error;
		}

		// log error in logfile
		if (!is_int($this->config['output']['file'])) {
			die(__CLASS__ . ': debug.output.file has to a valid PHP timestamp.');
		}

		if (time() < $this->config['output']['file']) {
			$this->_errorhandler_file($errstr, $backtrace, $errordescription);
		}

		// trigger event/hook
		if ($this->_event_object !== null) {
			$this->_event_object->trigger('core.after_exception', $exception);
		}
	}
31983
public function exceptionHandler($exception)
    {
        $this->lastHandledException = $exception;

        $this->client->catchException($exception);

        if ($this->oldExceptionHandler) {
            call_user_func(
                $this->oldExceptionHandler,
                $exception
            );
        }
    }
840325
public static function handleException($exception)
    {
        $message = get_class($exception) . " " . $exception->getCode() . ":\n\n" . $exception->getMessage() . "\n" .
            self::exception_get_dev_message($exception) . " in " .
            $exception->getFile() . " on line " . $exception->getLine() . ".\n\n Backtrace: " . $exception->getTraceAsString();

        $currentPreviousException = $exception;
        while ($currentPreviousException = $currentPreviousException->getPrevious()) {
            $message .= "\nPrevious: " . get_class($currentPreviousException) . " " . $currentPreviousException->getMessage() . "\n" . self::exception_get_dev_message($currentPreviousException) . "\n in "
                . $currentPreviousException->getFile() . " on line " . $currentPreviousException->getLine() . ".\n" . $currentPreviousException->getTraceAsString();
        }

        if (self::isDeveloperPresentable($exception)) {
            $uri = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : (isset($_SERVER["argv"]) ? implode(" ", $_SERVER["argv"]) : null);

            Logger::log($message, Logger::LOG_LEVEL_ERROR);

            $debugMsg = $message . "\n\n\n" . "URL: " . $uri . " \nPOST: ".print_r($_POST, true).
                "GET: " . print_r($_GET, true) .
                "SERVER: " . print_r($_SERVER, true) .
                "HTTP: " . print_r(getallheaders(), true) .
                "\nComposer: " . print_r(GomaENV::getProjectLevelComposerArray(), true) .
                " Installed: " . print_r(GomaENV::getProjectLevelInstalledComposerArray(), true) . "\n\n";
            Logger::log($debugMsg, Logger::LOG_LEVEL_DEBUG);
        } else {
            Logger::log($message, Logger::LOG_LEVEL_LOG);
        }
    }
1140565
static function catchException($exception)
    {
        $str = '';
        if ($exception instanceof \ErrorException) {
            $str .= static::severity2string($exception->getSeverity()) . ': ';
        }
        $str .= $exception->__toString();
        if (ini_get('display_errors')) {
            echo $str . "\n\n";
        }
        if (ini_get('log_errors')) {
            error_log($str);
        }
    }
660691
public function handlerTerse(\Exception $exception)
    {
        if (!headers_sent()) {
            header('HTTP/1.1 500 Internal Server Error', true, 500);
            header('Content-type: text/plain; charset=UTF-8');
        }
        echo sprintf('Bad Moss: %s ( %s at line: %u )', $exception->getMessage(), $exception->getFile(), $exception->getLine());
    }
539348
private static function _formatTrace($exception)
    {
        $message = '';
        $i = 0;
        $trace = $exception->getTrace();
        array_shift($trace);
        foreach ($trace as $row) {
            $i++;
            $message .= "\n" . '#' . $i;
            $message .= isset($row['file']) ? ' ' . $row['file'] : '';
            $message .= isset($row['line']) ? '(' . $row['line'] . ')' : '';
            $message .= isset($row['class']) ? ' ' . $row['class'] . '::' : '';
            $message .= isset($row['function']) ? (isset($row['class']) ? '' : ' ') . $row['function'] . '(' : '';
            $message .= isset($row['args']) ? json_encode($row['args']) . ')' : '';
        }
        return $message;
    }