| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- namespace App\Module\Transfer\Exceptions;
- use Exception;
- /**
- * Transfer模块异常基类
- */
- class TransferException extends Exception
- {
- protected array $context = [];
- public function __construct(string $message = '', int $code = 0, ?Exception $previous = null, array $context = [])
- {
- parent::__construct($message, $code, $previous);
- $this->context = $context;
- }
- /**
- * 获取异常上下文信息
- */
- public function getContext(): array
- {
- return $this->context;
- }
- /**
- * 设置异常上下文信息
- */
- public function setContext(array $context): self
- {
- $this->context = $context;
- return $this;
- }
- /**
- * 添加上下文信息
- */
- public function addContext(string $key, mixed $value): self
- {
- $this->context[$key] = $value;
- return $this;
- }
- /**
- * 转换为数组格式
- */
- public function toArray(): array
- {
- return [
- 'message' => $this->getMessage(),
- 'code' => $this->getCode(),
- 'file' => $this->getFile(),
- 'line' => $this->getLine(),
- 'context' => $this->context,
- 'trace' => $this->getTraceAsString(),
- ];
- }
- /**
- * 转换为JSON格式
- */
- public function toJson(): string
- {
- return json_encode($this->toArray(), JSON_UNESCAPED_UNICODE);
- }
- /**
- * 记录异常日志
- */
- public function log(string $level = 'error'): void
- {
- \Log::log($level, $this->getMessage(), [
- 'exception' => get_class($this),
- 'code' => $this->getCode(),
- 'file' => $this->getFile(),
- 'line' => $this->getLine(),
- 'context' => $this->context,
- ]);
- }
- }
|