Error.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace easyTask;
  3. use easyTask\Exception\ErrorException;
  4. use \Closure as Closure;
  5. /**
  6. * Class Error
  7. * @package easyTask
  8. */
  9. class Error
  10. {
  11. /**
  12. * Register Error
  13. */
  14. public static function register()
  15. {
  16. error_reporting(E_ALL);
  17. set_error_handler([__CLASS__, 'appError']);
  18. set_exception_handler([__CLASS__, 'appException']);
  19. register_shutdown_function([__CLASS__, 'appShutdown']);
  20. }
  21. /**
  22. * appError
  23. * (E_ERROR|E_PARSE|E_CORE_ERROR|E_CORE_WARNING|E_COMPILE_ERROR|E_COMPILE_WARNING|E_STRICT)
  24. * @param string $errno
  25. * @param string $errStr
  26. * @param string $errFile
  27. * @param int $errLine
  28. * @throws
  29. */
  30. public static function appError($errno, $errStr, $errFile, $errLine)
  31. {
  32. //组装异常
  33. $type = 'error';
  34. $exception = new ErrorException($errno, $errStr, $errFile, $errLine);
  35. //日志记录
  36. static::report($type, $exception);
  37. }
  38. /**
  39. * appException
  40. * @param mixed $exception (Exception|Throwable)
  41. * @throws
  42. */
  43. public static function appException($exception)
  44. {
  45. //日志记录
  46. $type = 'exception';
  47. static::report($type, $exception);
  48. }
  49. /**
  50. * appShutdown
  51. * (Fatal Error|Parse Error)
  52. * @throws
  53. */
  54. public static function appShutdown()
  55. {
  56. //存在错误
  57. $type = 'warring';
  58. if (($error = error_get_last()) != null)
  59. {
  60. //日志记录
  61. $exception = new ErrorException($error['type'], $error['message'], $error['file'], $error['line']);
  62. static::report($type, $exception);
  63. }
  64. }
  65. /**
  66. * Report
  67. * @param string $type
  68. * @param ErrorException $exception
  69. */
  70. public static function report($type, $exception)
  71. {
  72. //标准化日志
  73. $text = Helper::formatException($exception, $type);
  74. //本地日志储存
  75. Helper::writeLog($text);
  76. //同步模式输出
  77. if (!Env::get('daemon')) echo($text);
  78. //回调上报信息
  79. $notify = Env::get('notifyHand');
  80. if ($notify)
  81. {
  82. //闭包回调
  83. if ($notify instanceof Closure)
  84. {
  85. $notify($exception);
  86. return;
  87. }
  88. //Http回调
  89. $request = [
  90. 'errStr' => $exception->getMessage(),
  91. 'errFile' => $exception->getFile(),
  92. 'errLine' => $exception->getLine(),
  93. ];
  94. $result = Helper::curl($notify, $request);
  95. if (!$result || $result != 'success')
  96. {
  97. Helper::showError("request http api $notify failed", false, 'warring', true);
  98. }
  99. }
  100. }
  101. }