|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Core; |
| 4 | + |
| 5 | +/** |
| 6 | + * Error and exception handler |
| 7 | + * |
| 8 | + * PHP version 5.4 |
| 9 | + */ |
| 10 | +class Error |
| 11 | +{ |
| 12 | + |
| 13 | + /** |
| 14 | + * Error handler. Convert all errors to Exceptions by throwing an ErrorException. |
| 15 | + * |
| 16 | + * @param int $level Error level |
| 17 | + * @param string $message Error message |
| 18 | + * @param string $file Filename the error was raised in |
| 19 | + * @param int $line Line number in the file |
| 20 | + * |
| 21 | + * @return void |
| 22 | + */ |
| 23 | + public static function errorHandler($level, $message, $file, $line) |
| 24 | + { |
| 25 | + if (error_reporting() !== 0) { // to keep the @ operator working |
| 26 | + throw new \ErrorException($message, 0, $level, $file, $line); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Exception handler. |
| 32 | + * |
| 33 | + * @param Exception $exception The exception |
| 34 | + * |
| 35 | + * @return void |
| 36 | + */ |
| 37 | + public static function exceptionHandler($exception) |
| 38 | + { |
| 39 | + // Code is 404 (not found) or 500 (general error) |
| 40 | + $code = $exception->getCode(); |
| 41 | + if ($code != 404) { |
| 42 | + $code = 500; |
| 43 | + } |
| 44 | + http_response_code($code); |
| 45 | + |
| 46 | + if (\App\Config::SHOW_ERRORS) { |
| 47 | + echo "<h1>Fatal error</h1>"; |
| 48 | + echo "<p>Uncaught exception: '" . get_class($exception) . "'</p>"; |
| 49 | + echo "<p>Message: '" . $exception->getMessage() . "'</p>"; |
| 50 | + echo "<p>Stack trace:<pre>" . $exception->getTraceAsString() . "</pre></p>"; |
| 51 | + echo "<p>Thrown in '" . $exception->getFile() . "' on line " . $exception->getLine() . "</p>"; |
| 52 | + } else { |
| 53 | + $log = dirname(__DIR__) . '/logs/' . date('Y-m-d') . '.txt'; |
| 54 | + ini_set('error_log', $log); |
| 55 | + |
| 56 | + $message = "Uncaught exception: '" . get_class($exception) . "'"; |
| 57 | + $message .= " with message '" . $exception->getMessage() . "'"; |
| 58 | + $message .= "\nStack trace: " . $exception->getTraceAsString(); |
| 59 | + $message .= "\nThrown in '" . $exception->getFile() . "' on line " . $exception->getLine(); |
| 60 | + |
| 61 | + error_log($message); |
| 62 | + |
| 63 | + View::renderTemplate("$code.html"); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments