Skip to content

Commit 6f8f059

Browse files
Justin Hayesfaustbrian
authored andcommitted
[Slack] Throw guzzle client exception when slack api request fails (#40)
1 parent a0d676a commit 6f8f059

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Provider.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
namespace SocialiteProviders\Slack;
44

5+
use GuzzleHttp\Client;
6+
use GuzzleHttp\HandlerStack;
7+
use Psr\Http\Message\ResponseInterface;
8+
use GuzzleHttp\Exception\RequestException;
59
use SocialiteProviders\Manager\OAuth2\User;
610
use Laravel\Socialite\Two\ProviderInterface;
711
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
@@ -25,6 +29,50 @@ class Provider extends AbstractProvider implements ProviderInterface
2529
*/
2630
protected $scopeSeparator = ',';
2731

32+
/**
33+
* Middleware that throws exceptions for non successful slack api calls
34+
* "http_error" request option is set to true.
35+
*
36+
* @return callable Returns a function that accepts the next handler.
37+
*/
38+
private function getSlackApiErrorMiddleware()
39+
{
40+
return function (callable $handler) {
41+
return function ($request, array $options) use ($handler) {
42+
if (empty($options['http_errors'])) {
43+
return $handler($request, $options);
44+
}
45+
return $handler($request, $options)->then(
46+
function (ResponseInterface $response) use ($request, $handler) {
47+
$body = json_decode($response->getBody()->getContents(), true);
48+
$response->getBody()->rewind();
49+
50+
if ($body['ok']) {
51+
return $response;
52+
}
53+
54+
throw RequestException::create($request, $response);
55+
}
56+
);
57+
};
58+
};
59+
}
60+
61+
/**
62+
* {@inheritdoc}
63+
*/
64+
protected function getHttpClient()
65+
{
66+
$handler = HandlerStack::create();
67+
$handler->push($this->getSlackApiErrorMiddleware(), 'slack_api_errors');
68+
69+
if (is_null($this->httpClient)) {
70+
$this->httpClient = new Client(['handler' => $handler]);
71+
}
72+
73+
return $this->httpClient;
74+
}
75+
2876
/**
2977
* {@inheritdoc}
3078
*/

0 commit comments

Comments
 (0)