DebugEvent.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace addons\shopro\library\chat\traits;
  3. use addons\shopro\exception\ShoproException;
  4. /**
  5. * debug 方式注册事件
  6. */
  7. trait DebugEvent
  8. {
  9. /**
  10. * 注册事件
  11. */
  12. public function register($event, \Closure $cb)
  13. {
  14. $this->socket->on($event, function ($data, $callback = null) use ($cb) {
  15. try {
  16. $cb($data, $callback);
  17. } catch (\Exception $e) {
  18. $this->errorHandler($e, 'register');
  19. // 将错误报告给前端
  20. $this->sender->errorSocket('custom_error', ($this->io->debug || $e instanceof ShoproException) ? $e->getMessage() : 'socket 服务器异常');
  21. }
  22. });
  23. }
  24. /**
  25. * 执行代码
  26. *
  27. * @param object $httpConnection 当前 socket 连接
  28. * @param \Closure $callback
  29. * @return void
  30. */
  31. public function exec($httpConnection, \Closure $callback)
  32. {
  33. try {
  34. $callback();
  35. } catch (\Exception $e) {
  36. $this->errorHandler($e, 'exec');
  37. // 将错误报告给前端
  38. $httpConnection->send(($this->io->debug || $e instanceof ShoproException) ? $e->getMessage() : 'socket 服务器异常');
  39. }
  40. }
  41. /**
  42. * 判断处理异常
  43. *
  44. * @param \Exception $e
  45. * @param string $type
  46. * @return void
  47. */
  48. private function errorHandler(\Exception $e, $type)
  49. {
  50. $error = [
  51. 'line' => $e->getLine(),
  52. 'file' => $e->getFile(),
  53. 'error' => $e->getMessage()
  54. // 'trace' => $e->getTrace(),
  55. ];
  56. if ($this->io->debug) {
  57. echo 'websocket:' . $type . ':执行失败,错误信息:' . json_encode($error, JSON_UNESCAPED_UNICODE);
  58. } else {
  59. format_log_error($e, 'WebSocket', 'WebSocket 执行失败');
  60. }
  61. }
  62. }