ExceptionMiddleware.php 2.2 KB

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