diff --git a/src/Executor/ExecutionResult.php b/src/Executor/ExecutionResult.php index 6666bbc..b868b8f 100644 --- a/src/Executor/ExecutionResult.php +++ b/src/Executor/ExecutionResult.php @@ -17,7 +17,7 @@ class ExecutionResult implements \JsonSerializable public $errors; /** - * @var array[] + * @var array */ public $extensions; @@ -26,6 +26,11 @@ class ExecutionResult implements \JsonSerializable */ private $errorFormatter; + /** + * @var callable + */ + private $errorsHandler; + /** * @param array $data * @param array $errors @@ -39,6 +44,18 @@ class ExecutionResult implements \JsonSerializable } /** + * Define custom error formatting (must conform to http://facebook.github.io/graphql/#sec-Errors) + * + * Expected signature is: function (GraphQL\Error\Error $error): array + * + * Default formatter is "GraphQL\Error\FormattedError::createFromException" + * + * Expected returned value must be an array: + * array( + * 'message' => 'errorMessage', + * // ... other keys + * ); + * * @param callable $errorFormatter * @return $this */ @@ -49,6 +66,30 @@ class ExecutionResult implements \JsonSerializable } /** + * Define custom logic for error handling (filtering, logging, etc). + * + * Expected handler signature is: function (array $errors, callable $formatter): array + * + * Default handler is: + * function (array $errors, callable $formatter) { + * return array_map($formatter, $errors); + * } + * + * @param callable $handler + * @return $this + */ + public function setErrorsHandler(callable $handler) + { + $this->errorsHandler = $handler; + return $this; + } + + /** + * Converts GraphQL result to array using provided errors handler and formatter. + * + * Default error formatter is GraphQL\Error\FormattedError::createFromException + * Default error handler will simply return all errors formatted. No errors are filtered. + * * @param bool|int $debug * @return array */ @@ -68,7 +109,12 @@ class ExecutionResult implements \JsonSerializable } else { $errorFormatter = $this->errorFormatter; } - $result['errors'] = array_map($errorFormatter, $this->errors); + + $errorsHandler = $this->errorsHandler ?: function(array $errors, callable $formatter) { + return array_map($formatter, $errors); + }; + + $result['errors'] = $errorsHandler($this->errors, $errorFormatter); } if (null !== $this->data) { @@ -82,6 +128,11 @@ class ExecutionResult implements \JsonSerializable return $result; } + /** + * Part of \JsonSerializable interface + * + * @return array + */ public function jsonSerialize() { return $this->toArray();