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, ]); } }