From 78d067481bff56897fdb48e46a179d7b419081ea Mon Sep 17 00:00:00 2001 From: Heinz Wiesinger Date: Wed, 29 Sep 2021 11:24:55 +0200 Subject: [PATCH] Requests: Add "requests.failed" hook This allows to inspect or alter the exception that is thrown to the user in case of transport errors, or in case of response parsing problems. --- docs/hooks.md | 7 +++++++ src/Requests.php | 15 ++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/hooks.md b/docs/hooks.md index 59e628a6b..6e6aaa146 100644 --- a/docs/hooks.md +++ b/docs/hooks.md @@ -31,6 +31,13 @@ Available Hooks Parameters: `WpOrg\Requests\Response &$return` +* **`requests.failed`** + + Alter/Inspect transport or response parsing exception before it is returned to the user. + + Parameters: `Requests_Exception &$exception`, `string $url`, `array $headers`, `array|string $data`, + `string $type`, `array $options` + * **`curl.before_request`** Set cURL options before the transport sets any (note that Requests may diff --git a/src/Requests.php b/src/Requests.php index ab3b3a7e9..87adde908 100644 --- a/src/Requests.php +++ b/src/Requests.php @@ -426,11 +426,20 @@ public static function request($url, $headers = array(), $data = array(), $type $capabilities = array('ssl' => $need_ssl); $transport = self::get_transport($capabilities); } - $response = $transport->request($url, $headers, $data, $options); - $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options)); + try { + $response = $transport->request($url, $headers, $data, $options); + + $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options)); + + $parsed_response = self::parse_response($response, $url, $headers, $data, $options); + } + catch (Requests_Exception $e) { + $options['hooks']->dispatch('requests.failed', array($e, $url, $headers, $data, $type, $options)); + throw $e; + } - return self::parse_response($response, $url, $headers, $data, $options); + return $parsed_response; } /**