ErrorHandler.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Aliyun\OTS\Handlers;
  3. use Aliyun\OTS;
  4. class ErrorHandler
  5. {
  6. private function logOTSServerException(RequestContext $context, \Aliyun\OTS\OTSServerException $exception)
  7. {
  8. $errorLogger = $context->clientConfig->errorLogHandler;
  9. if ($errorLogger != null) {
  10. $errorLogger((string)$exception);
  11. }
  12. }
  13. public function handleBefore(RequestContext $context)
  14. {
  15. // empty
  16. }
  17. public function handleAfter(RequestContext $context)
  18. {
  19. if ($context->responseHttpStatus >= 200 && $context->responseHttpStatus < 300) {
  20. return;
  21. }
  22. $error = new \PBError();
  23. $errorCode = null;
  24. $errorMessage = null;
  25. try {
  26. $error->ParseFromString($context->responseBody);
  27. $errorCode = $error->code();
  28. $errorMessage = $error->message();
  29. } catch (\Exception $e) {
  30. // Sometimes the response body is not a valid Error PB Message,
  31. // in this case the user should get informed with http status
  32. $exception = new \Aliyun\OTS\OTSServerException($context->apiName, $context->responseHttpStatus);
  33. $this->logOTSServerException($context, $exception);
  34. $context->otsServerException = $exception;
  35. return;
  36. }
  37. $requestId = null;
  38. if (isset($context->responseHeaders['x-ots-requestid'])) {
  39. $requestId = $context->responseHeaders['x-ots-requestid'];
  40. }
  41. $exception = new \Aliyun\OTS\OTSServerException(
  42. $context->apiName, $context->responseHttpStatus,
  43. $errorCode, $errorMessage, $requestId);
  44. $this->logOTSServerException($context, $exception);
  45. $context->otsServerException = $exception;
  46. }
  47. }