ExceptionMiddleware.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Qcloud\Cos;
  3. use Qcloud\Cos\Exception\ServiceResponseException;
  4. use GuzzleHttp\Promise\PromiseInterface;
  5. use GuzzleHttp\Psr7;
  6. use Psr\Http\Message\RequestInterface;
  7. use Psr\Http\Message\ResponseInterface;
  8. use GuzzleHttp\Exception\RequestException;
  9. class ExceptionMiddleware {
  10. private $nextHandler;
  11. protected $parser;
  12. protected $defaultException;
  13. /**
  14. * @param callable $nextHandler Next handler to invoke.
  15. */
  16. public function __construct(callable $nextHandler) {
  17. $this->nextHandler = $nextHandler;
  18. $this->parser = new ExceptionParser();
  19. $this->defaultException = 'Qcloud\Cos\Exception\ServiceResponseException';
  20. }
  21. /**
  22. * @param RequestInterface $request
  23. * @param array $options
  24. *
  25. * @return PromiseInterface
  26. */
  27. public function __invoke(RequestInterface $request, array $options) {
  28. $fn = $this->nextHandler;
  29. return $fn($request, $options)->then(
  30. function (ResponseInterface $response) use ($request) {
  31. return $this->handle($request, $response);
  32. }
  33. );
  34. }
  35. public function handle(RequestInterface $request, ResponseInterface $response) {
  36. $code = $response->getStatusCode();
  37. if ($code < 400) {
  38. return $response;
  39. }
  40. //throw RequestException::create($request, $response);
  41. $parts = $this->parser->parse($request, $response);
  42. $className = 'Qcloud\\Cos\\Exception\\' . $parts['code'];
  43. if (substr($className, -9) !== 'Exception') {
  44. $className .= 'Exception';
  45. }
  46. $className = class_exists($className) ? $className : $this->defaultException;
  47. throw $this->createException($className, $request, $response, $parts);
  48. }
  49. protected function createException($className, RequestInterface $request, ResponseInterface $response, array $parts) {
  50. $class = new $className($parts['message']);
  51. if ($class instanceof ServiceResponseException) {
  52. $class->setExceptionCode($parts['code']);
  53. $class->setExceptionType($parts['type']);
  54. $class->setResponse($response);
  55. $class->setRequest($request);
  56. $class->setRequestId($parts['request_id']);
  57. }
  58. return $class;
  59. }
  60. }