Skip to content

Commit

Permalink
Requests: Add "requests.failed" hook
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
pprkut committed Oct 26, 2021
1 parent 2d78a4d commit 78d0674
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
7 changes: 7 additions & 0 deletions docs/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 12 additions & 3 deletions src/Requests.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down

0 comments on commit 78d0674

Please sign in to comment.