HttpException.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Http\Client\Exception;
  3. use Psr\Http\Message\RequestInterface;
  4. use Psr\Http\Message\ResponseInterface;
  5. /**
  6. * Thrown when a response was received but the request itself failed.
  7. *
  8. * In addition to the request, this exception always provides access to the response object.
  9. *
  10. * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
  11. */
  12. class HttpException extends RequestException
  13. {
  14. /**
  15. * @var ResponseInterface
  16. */
  17. protected $response;
  18. /**
  19. * @param string $message
  20. */
  21. public function __construct(
  22. $message,
  23. RequestInterface $request,
  24. ResponseInterface $response,
  25. \Exception $previous = null
  26. ) {
  27. parent::__construct($message, $request, $previous);
  28. $this->response = $response;
  29. $this->code = $response->getStatusCode();
  30. }
  31. /**
  32. * Returns the response.
  33. *
  34. * @return ResponseInterface
  35. */
  36. public function getResponse()
  37. {
  38. return $this->response;
  39. }
  40. /**
  41. * Factory method to create a new exception with a normalized error message.
  42. */
  43. public static function create(
  44. RequestInterface $request,
  45. ResponseInterface $response,
  46. \Exception $previous = null
  47. ) {
  48. $message = sprintf(
  49. '[url] %s [http method] %s [status code] %s [reason phrase] %s',
  50. $request->getRequestTarget(),
  51. $request->getMethod(),
  52. $response->getStatusCode(),
  53. $response->getReasonPhrase()
  54. );
  55. return new static($message, $request, $response, $previous);
  56. }
  57. }