From f7c09cb7ff84db1004a4fa83a70735475702023f Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Fri, 20 Jan 2017 21:12:19 +0100 Subject: Added exception handler --- composer.json | 5 ++ includes/engelsystem_provider.php | 10 ++++ src/Exceptions/Handler.php | 97 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 src/Exceptions/Handler.php diff --git a/composer.json b/composer.json index 5b2498da..bb21de23 100644 --- a/composer.json +++ b/composer.json @@ -17,5 +17,10 @@ "php": ">=5.4", "erusev/parsedown": "1.6.*", "twbs/bootstrap": "^3.3" + }, + "autoload": { + "psr-4": { + "Engelsystem\\": "src/" + } } } diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index 1a5f5d86..3f46e4ab 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -1,4 +1,7 @@ environment = $environment; + + set_error_handler([$this, 'errorHandler']); + set_exception_handler([$this, 'exceptionHandler']); + } + + /** + * @param int $number + * @param string $string + * @param string $file + * @param int $line + * @param array $context + */ + public function errorHandler($number, $string, $file, $line, $context) + { + $this->handle('error', $number, $string, $file, $line, $context); + } + + /** + * @param Exception $e + */ + public function exceptionHandler(Exception $e) + { + $this->handle( + 'exception', + $e->getCode(), + get_class($e) . ': ' . $e->getMessage(), + $e->getFile(), + $e->getLine() + ); + } + + /** + * @param string $type + * @param int $number + * @param string $string + * @param string $file + * @param int $line + * @param array $context + */ + protected function handle($type, $number, $string, $file, $line, $context = []) + { + error_log(sprintf('%s: Number: %s, String: %s, File: %s:%u, Context: %s', + $type, + $number, + $string, + $file, + $line, + json_encode($context) + )); + + if ($this->environment == self::ENV_DEVELOPMENT || $this->environment == self::ENV_DEBUGGING) { + echo '
';
+            echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number);
+            var_export([
+                'string'  => $string,
+                'file'    => $file . ':' . $line,
+                'context' => ($this->environment == self::ENV_DEBUGGING ? $context : null),
+            ]);
+            echo '
'; + die(); + } + + echo 'An unexpected error occurred, a team of untrained monkeys has been dispatched to deal with it.'; + die(); + } + + /** + * @param string $environment + */ + public function setEnvironment($environment) + { + $this->environment = $environment; + } +} -- cgit v1.2.3-54-g00ecf