Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 7022ce0

Browse files
committedDec 17, 2021
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.
1 parent 73dbbbe commit 7022ce0

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed
 

‎docs/hooks.md

+7
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ Available Hooks
3131

3232
Parameters: `WpOrg\Requests\Response &$return`
3333

34+
* **`requests.failed`**
35+
36+
Alter/Inspect transport or response parsing exception before it is returned to the user.
37+
38+
Parameters: `WpOrg\Requests\Exception|WpOrg\Requests\Exception\InvalidArgument &$exception`, `string $url`, `array $headers`, `array|string $data`,
39+
`string $type`, `array $options`
40+
3441
* **`curl.before_request`**
3542

3643
Set cURL options before the transport sets any (note that Requests may

‎src/Requests.php

+15-3
Original file line numberDiff line numberDiff line change
@@ -466,11 +466,23 @@ public static function request($url, $headers = [], $data = [], $type = self::GE
466466
$transport = self::get_transport($capabilities);
467467
}
468468

469-
$response = $transport->request($url, $headers, $data, $options);
469+
try {
470+
$response = $transport->request($url, $headers, $data, $options);
471+
472+
$options['hooks']->dispatch('requests.before_parse', [&$response, $url, $headers, $data, $type, $options]);
470473

471-
$options['hooks']->dispatch('requests.before_parse', [&$response, $url, $headers, $data, $type, $options]);
474+
$parsed_response = self::parse_response($response, $url, $headers, $data, $options);
475+
}
476+
catch (Exception $e) {
477+
$options['hooks']->dispatch('requests.failed', [$e, $url, $headers, $data, $type, $options]);
478+
throw $e;
479+
}
480+
catch (InvalidArgument $e) {
481+
$options['hooks']->dispatch('requests.failed', [$e, $url, $headers, $data, $type, $options]);
482+
throw $e;
483+
}
472484

473-
return self::parse_response($response, $url, $headers, $data, $options);
485+
return $parsed_response;
474486
}
475487

476488
/**

0 commit comments

Comments
 (0)
Please sign in to comment.