Skip to content

Commit 78d0674

Browse files
committed
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 2d78a4d commit 78d0674

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-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: `Requests_Exception &$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

+12-3
Original file line numberDiff line numberDiff line change
@@ -426,11 +426,20 @@ public static function request($url, $headers = array(), $data = array(), $type
426426
$capabilities = array('ssl' => $need_ssl);
427427
$transport = self::get_transport($capabilities);
428428
}
429-
$response = $transport->request($url, $headers, $data, $options);
430429

431-
$options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options));
430+
try {
431+
$response = $transport->request($url, $headers, $data, $options);
432+
433+
$options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options));
434+
435+
$parsed_response = self::parse_response($response, $url, $headers, $data, $options);
436+
}
437+
catch (Requests_Exception $e) {
438+
$options['hooks']->dispatch('requests.failed', array($e, $url, $headers, $data, $type, $options));
439+
throw $e;
440+
}
432441

433-
return self::parse_response($response, $url, $headers, $data, $options);
442+
return $parsed_response;
434443
}
435444

436445
/**

0 commit comments

Comments
 (0)