ExceptionFormatter.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Framework\GraphQl\Exception;
  8. use Magento\Framework\App\State;
  9. use Magento\Framework\Webapi\ErrorProcessor;
  10. use Psr\Log\LoggerInterface;
  11. /**
  12. * Wrapper for GraphQl Exception Formatter
  13. */
  14. class ExceptionFormatter
  15. {
  16. const HTTP_GRAPH_QL_SCHEMA_ERROR_STATUS = 500;
  17. /**
  18. * @var State
  19. */
  20. private $appState;
  21. /**
  22. * @var LoggerInterface
  23. */
  24. private $logger;
  25. /**
  26. * @param State $appState
  27. * @param ErrorProcessor $errorProcessor
  28. */
  29. public function __construct(State $appState, ErrorProcessor $errorProcessor, LoggerInterface $logger)
  30. {
  31. $this->appState = $appState;
  32. $errorProcessor->registerShutdownFunction();
  33. $this->logger = $logger;
  34. }
  35. /**
  36. * Format a GraphQL error from an exception by converting it to array to conform to GraphQL spec.
  37. *
  38. * This method only exposes exception message when exception implements ClientAware interface
  39. * (or when debug flags are passed).
  40. *
  41. * @param \Throwable $exception
  42. * @param string $internalErrorMessage
  43. * @return array
  44. * @throws \Throwable
  45. */
  46. public function create(\Throwable $exception, $internalErrorMessage = null) : array
  47. {
  48. if (!$this->shouldShowDetail()) {
  49. $reportId = uniqid("graph-ql-");
  50. $message = "Report ID: {$reportId}; Message: {$exception->getMessage()}";
  51. $code = $exception->getCode();
  52. $loggedException = new \Exception($message, $code, $exception);
  53. $this->logger->critical($loggedException);
  54. }
  55. return \GraphQL\Error\FormattedError::createFromException(
  56. $exception,
  57. $this->shouldShowDetail()
  58. ? \GraphQL\Error\Debug::INCLUDE_DEBUG_MESSAGE | \GraphQL\Error\Debug::INCLUDE_TRACE : false,
  59. $internalErrorMessage
  60. );
  61. }
  62. /**
  63. * Return true if detailed error message should be displayed to client, false otherwise.
  64. *
  65. * @return bool
  66. */
  67. public function shouldShowDetail() : bool
  68. {
  69. return $this->appState->getMode() === State::MODE_DEVELOPER;
  70. }
  71. }