ErrorHandler.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2020 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
11 namespace wcmf\lib\core;
12 
13 /**
14  * ErrorHandler catches all php errors and transforms fatal
15  * errors into ErrorExceptions and non-fatal into log messages
16  *
17  * @author ingo herwig <ingo@wemove.com>
18  */
19 class ErrorHandler {
20 
21  // fatal errors that can be handled with a user defined function
22  private static $fatalErrors = [E_USER_ERROR => '', E_RECOVERABLE_ERROR => ''];
23 
24  private static $logger = null;
25 
26  /**
27  * Constructor
28  * @param $setExceptionHandler Boolean indicating, if this instance should also set
29  * an exception handler to log exceptions (default: __false__)
30  */
31  public function __construct($setExceptionHandler=false) {
32  set_error_handler([$this, 'handleError']);
33  if ($setExceptionHandler) {
34  set_exception_handler([$this, 'handleException']);
35  }
36  if (self::$logger == null) {
37  self::$logger = LogManager::getLogger(__CLASS__);
38  }
39  }
40 
41  /**
42  * Get the stack trace
43  * @return The stack trace as string
44  */
45  public static function getStackTrace() {
46  ob_start();
47  debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
48  $trace = ob_get_contents();
49  ob_end_clean();
50 
51  // remove first item from backtrace as it's this function which is redundant.
52  $trace = preg_replace('/^#0\s+'.__FUNCTION__."[^\n]*\n/", '', $trace, 1);
53 
54  return $trace;
55  }
56 
57  /**
58  * Error handler
59  * @param $errno
60  * @param $errstr
61  * @param $errfile
62  * @param $errline
63  * @return Boolean
64  * @throws ErrorException
65  */
66  public function handleError($errno, $errstr, $errfile, $errline) {
67  $errorIsEnabled = (bool)($errno & ini_get('error_reporting'));
68 
69  // FATAL ERROR
70  if(isset(self::$fatalErrors[$errno]) && $errorIsEnabled) {
71  throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
72  }
73 
74  // NON-FATAL ERROR/WARNING/NOTICE
75  else if($errorIsEnabled) {
76  $info = $errstr." in ".$errfile." on line ".$errline;
77  self::$logger->logByErrorType($errno, $info);
78  }
79  }
80 
81  /**
82  * Exception handler
83  * @param $ex
84  */
85  public function handleException($ex) {
86  self::$logger->error($ex);
87  }
88 }
89 ?>
__construct($setExceptionHandler=false)
Constructor.
static getStackTrace()
Get the stack trace.
handleError($errno, $errstr, $errfile, $errline)
Error handler.
static getLogger($name)
Get the logger with the given name.
Definition: LogManager.php:37
Core classes.
Definition: namespaces.php:11
handleException($ex)
Exception handler.
ErrorHandler catches all php errors and transforms fatal errors into ErrorExceptions and non-fatal in...