CPSError.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace app\common\utility;
  3. use think\Log;
  4. define('CPS_FATAL', E_ERROR | E_USER_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR| E_PARSE | E_STRICT);
  5. class CPSError{
  6. private $errCode = array (
  7. E_ERROR => 'Error',
  8. E_WARNING => 'Warning',
  9. E_PARSE => 'Parsing Error',
  10. E_NOTICE => 'Notice',
  11. E_CORE_ERROR => 'Core Error',
  12. E_CORE_WARNING => 'Core Warning',
  13. E_COMPILE_ERROR => 'Compile Error',
  14. E_COMPILE_WARNING => 'Compile Warning',
  15. E_USER_ERROR => 'User Error',
  16. E_USER_WARNING => 'User Warning',
  17. E_USER_NOTICE => 'User Notice',
  18. E_STRICT => 'Runtime Notice',
  19. E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
  20. );
  21. /**
  22. * 单例对象
  23. */
  24. protected static $instance;
  25. /**
  26. * 初始化
  27. * @access public
  28. */
  29. public static function hanndle(){
  30. if (is_null(self::$instance)) {
  31. self::$instance = new static();
  32. }
  33. return self::$instance;
  34. }
  35. /**
  36. * 构造函数
  37. * CPSError constructor.
  38. */
  39. private function __construct(){
  40. error_reporting(E_ALL);
  41. @register_shutdown_function([$this,'hanndleFatal']);
  42. @set_error_handler([$this, 'writeLogAndThrowExcption']);
  43. }
  44. /**
  45. * 错误处理
  46. * @throws \Exception
  47. */
  48. public function hanndleFatal(){
  49. $error = error_get_last();
  50. if($error && ($error["type"]===($error["type"] & CPS_FATAL))) {
  51. $this->writeLogAndThrowExcption($error["type"], $error["message"], $error["file"], $error["line"]);
  52. }
  53. }
  54. /**
  55. * 写日志信息
  56. * @param $errno
  57. * @param $errmsg
  58. * @param $filename
  59. * @param $linenum
  60. * @throws \Exception
  61. */
  62. public function writeLogAndThrowExcption($errno, $errmsg, $filename, $linenum)
  63. {
  64. Log::error('CPSException: Type:'.($this->errCode[$errno] ?? '未知错误').' Line:'.$linenum.' File:'.$filename.' Msg:'.$errmsg);
  65. throw new \Exception($errmsg);
  66. }
  67. public function __destruct(){
  68. restore_error_handler();
  69. }
  70. }