CommandException.php
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace GuzzleHttp\Command\Exception;
use GuzzleHttp\Command\CommandInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Exception encountered while executing a command.
*/
class CommandException extends \RuntimeException implements GuzzleException
{
/** @var CommandInterface */
private $command;
/** @var RequestInterface */
private $request;
/** @var ResponseInterface */
private $response;
/**
* @return CommandException
*/
public static function fromPrevious(CommandInterface $command, \Exception $prev)
{
// If the exception is already a command exception, return it.
if ($prev instanceof self && $command === $prev->getCommand()) {
return $prev;
}
// If the exception is a RequestException, get the Request and Response.
$request = $response = null;
if ($prev instanceof RequestException) {
$request = $prev->getRequest();
$response = $prev->getResponse();
}
// Throw a more specific exception for 4XX or 5XX responses.
$class = self::class;
$statusCode = $response ? $response->getStatusCode() : 0;
if ($statusCode >= 400 && $statusCode < 500) {
$class = CommandClientException::class;
} elseif ($statusCode >= 500 && $statusCode < 600) {
$class = CommandServerException::class;
}
// Prepare the message.
$message = 'There was an error executing the '.$command->getName()
.' command: '.$prev->getMessage();
// Create the exception.
return new $class($message, $command, $prev, $request, $response);
}
/**
* @param string $message Exception message
* @param \Exception|null $previous Previous exception (if any)
*/
public function __construct(
$message,
CommandInterface $command,
\Exception $previous = null,
RequestInterface $request = null,
ResponseInterface $response = null
) {
$this->command = $command;
$this->request = $request;
$this->response = $response;
parent::__construct($message, 0, $previous);
}
/**
* Gets the command that failed.
*
* @return CommandInterface
*/
public function getCommand()
{
return $this->command;
}
/**
* Gets the request that caused the exception
*
* @return RequestInterface|null
*/
public function getRequest()
{
return $this->request;
}
/**
* Gets the associated response
*
* @return ResponseInterface|null
*/
public function getResponse()
{
return $this->response;
}
}