apiUrl = $apiUrl; $this->method = $method; $this->requestData = $requestData; $this->responseData = $responseData; $this->httpStatus = $httpStatus; $context = [ 'api_url' => $apiUrl, 'method' => $method, 'request_data' => $requestData, 'response_data' => $responseData, 'http_status' => $httpStatus, ]; parent::__construct($message, 2001, null, $context); } /** * 获取API URL */ public function getApiUrl(): string { return $this->apiUrl; } /** * 获取请求方法 */ public function getMethod(): string { return $this->method; } /** * 获取请求数据 */ public function getRequestData(): array { return $this->requestData; } /** * 获取响应数据 */ public function getResponseData(): ?array { return $this->responseData; } /** * 获取HTTP状态码 */ public function getHttpStatus(): int { return $this->httpStatus; } /** * 判断是否为网络错误 */ public function isNetworkError(): bool { return $this->httpStatus === 0 || $this->httpStatus >= 500; } /** * 判断是否为客户端错误 */ public function isClientError(): bool { return $this->httpStatus >= 400 && $this->httpStatus < 500; } /** * 判断是否为服务器错误 */ public function isServerError(): bool { return $this->httpStatus >= 500; } /** * 判断是否可以重试 */ public function isRetryable(): bool { // 网络错误和服务器错误可以重试 return $this->isNetworkError() || $this->isServerError(); } /** * 获取详细错误信息 */ public function getDetailedMessage(): string { $message = sprintf( '外部API调用失败: %s %s (HTTP %d)', $this->method, $this->apiUrl, $this->httpStatus ); if ($this->responseData) { $responseMessage = $this->responseData['message'] ?? $this->responseData['error'] ?? ''; if ($responseMessage) { $message .= ' - ' . $responseMessage; } } return $message; } /** * 创建网络超时异常 */ public static function timeout(string $apiUrl, string $method, array $requestData = []): self { return new self( $apiUrl, $method, $requestData, null, 0, '外部API调用超时' ); } /** * 创建HTTP错误异常 */ public static function httpError( string $apiUrl, string $method, int $httpStatus, array $requestData = [], ?array $responseData = null ): self { $message = "外部API返回HTTP错误: {$httpStatus}"; return new self( $apiUrl, $method, $requestData, $responseData, $httpStatus, $message ); } /** * 创建响应格式错误异常 */ public static function invalidResponse( string $apiUrl, string $method, array $requestData = [], ?array $responseData = null ): self { return new self( $apiUrl, $method, $requestData, $responseData, 200, '外部API响应格式无效' ); } }