ExceptionWrapper.php
78 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Copyright (c) Microsoft Corporation. All Rights Reserved. |
| 4 | * Licensed under the MIT License. See License in the project root |
| 5 | * for license information. |
| 6 | * |
| 7 | * ExceptionWrapper File |
| 8 | * PHP version 7 |
| 9 | * |
| 10 | * @category Library |
| 11 | * @package Microsoft.Graph |
| 12 | * @copyright 2016 Microsoft Corporation |
| 13 | * @license https://opensource.org/licenses/MIT MIT License |
| 14 | * @version GIT: 0.1.0 |
| 15 | * @link https://graph.microsoft.io/ |
| 16 | */ |
| 17 | |
| 18 | namespace Microsoft\Graph\Core; |
| 19 | |
| 20 | use AmeliaVendor\GuzzleHttp\Exception\BadResponseException; |
| 21 | |
| 22 | /** |
| 23 | * Class ExceptionWrapper |
| 24 | * |
| 25 | * @category Library |
| 26 | * @package Microsoft.Graph |
| 27 | * @license https://opensource.org/licenses/MIT MIT License |
| 28 | * @link https://graph.microsoft.io/ |
| 29 | */ |
| 30 | class ExceptionWrapper |
| 31 | { |
| 32 | /** |
| 33 | * Wrap Guzzle BadResponseException which returns truncated exception messages for 4xx and 5xx responses. |
| 34 | * Adds response body to the exception message. |
| 35 | * |
| 36 | * @param BadResponseException $ex |
| 37 | * @return BadResponseException containing HTTP response from Graph API |
| 38 | */ |
| 39 | public static function wrapGuzzleBadResponseException(BadResponseException $ex) |
| 40 | { |
| 41 | $response = $ex->getResponse(); |
| 42 | |
| 43 | // Safety check for Guzzle < 7.0 |
| 44 | if (!$response) { |
| 45 | return $ex; |
| 46 | } |
| 47 | |
| 48 | /** @see \AmeliaVendor\GuzzleHttp\Exception\RequestException::create() */ |
| 49 | if (preg_match('/^(.+: `.+ .+` resulted in a `.+ .+` response):\n/U', $ex->getMessage(), $match)) { |
| 50 | $message = $match[1]; |
| 51 | |
| 52 | $body = $response->getBody(); |
| 53 | |
| 54 | if (!$body->isSeekable() || !$body->isReadable()) { |
| 55 | return $ex; |
| 56 | } |
| 57 | |
| 58 | $summary = $body->getContents(); |
| 59 | $body->rewind(); |
| 60 | |
| 61 | if ($summary !== '') { |
| 62 | $message .= ":\n{$summary}\n"; |
| 63 | |
| 64 | //return new $ex($message, $ex->getRequest(), $ex->getResponse(), $ex, $ex->getHandlerContext()); |
| 65 | // Better: modify internal message inside original exception object (preserves the stack trace) |
| 66 | (new class() extends \Exception { |
| 67 | public static function overwriteProtectedMessage(\Exception $ex, $message) |
| 68 | { |
| 69 | $ex->message = $message; |
| 70 | } |
| 71 | })::overwriteProtectedMessage($ex, $message); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | return $ex; |
| 76 | } |
| 77 | } |
| 78 |