Improved flexibility of error handling

This commit is contained in:
Vladimir Razuvaev 2017-08-17 02:11:21 +07:00
parent 1ee226465b
commit b56083b7de

View File

@ -17,7 +17,7 @@ class ExecutionResult implements \JsonSerializable
public $errors; public $errors;
/** /**
* @var array[] * @var array
*/ */
public $extensions; public $extensions;
@ -26,6 +26,11 @@ class ExecutionResult implements \JsonSerializable
*/ */
private $errorFormatter; private $errorFormatter;
/**
* @var callable
*/
private $errorsHandler;
/** /**
* @param array $data * @param array $data
* @param array $errors * @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 * @param callable $errorFormatter
* @return $this * @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 * @param bool|int $debug
* @return array * @return array
*/ */
@ -68,7 +109,12 @@ class ExecutionResult implements \JsonSerializable
} else { } else {
$errorFormatter = $this->errorFormatter; $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) { if (null !== $this->data) {
@ -82,6 +128,11 @@ class ExecutionResult implements \JsonSerializable
return $result; return $result;
} }
/**
* Part of \JsonSerializable interface
*
* @return array
*/
public function jsonSerialize() public function jsonSerialize()
{ {
return $this->toArray(); return $this->toArray();