TransferException.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Module\Transfer\Exceptions;
  3. use Exception;
  4. /**
  5. * Transfer模块异常基类
  6. */
  7. class TransferException extends Exception
  8. {
  9. protected array $context = [];
  10. public function __construct(string $message = '', int $code = 0, ?Exception $previous = null, array $context = [])
  11. {
  12. parent::__construct($message, $code, $previous);
  13. $this->context = $context;
  14. }
  15. /**
  16. * 获取异常上下文信息
  17. */
  18. public function getContext(): array
  19. {
  20. return $this->context;
  21. }
  22. /**
  23. * 设置异常上下文信息
  24. */
  25. public function setContext(array $context): self
  26. {
  27. $this->context = $context;
  28. return $this;
  29. }
  30. /**
  31. * 添加上下文信息
  32. */
  33. public function addContext(string $key, mixed $value): self
  34. {
  35. $this->context[$key] = $value;
  36. return $this;
  37. }
  38. /**
  39. * 转换为数组格式
  40. */
  41. public function toArray(): array
  42. {
  43. return [
  44. 'message' => $this->getMessage(),
  45. 'code' => $this->getCode(),
  46. 'file' => $this->getFile(),
  47. 'line' => $this->getLine(),
  48. 'context' => $this->context,
  49. 'trace' => $this->getTraceAsString(),
  50. ];
  51. }
  52. /**
  53. * 转换为JSON格式
  54. */
  55. public function toJson(): string
  56. {
  57. return json_encode($this->toArray(), JSON_UNESCAPED_UNICODE);
  58. }
  59. /**
  60. * 记录异常日志
  61. */
  62. public function log(string $level = 'error'): void
  63. {
  64. \Log::log($level, $this->getMessage(), [
  65. 'exception' => get_class($this),
  66. 'code' => $this->getCode(),
  67. 'file' => $this->getFile(),
  68. 'line' => $this->getLine(),
  69. 'context' => $this->context,
  70. ]);
  71. }
  72. }