Skip to content

Commit d7c96c7

Browse files
committed
add custom extensions to GraphQLErrors
1 parent da91f2e commit d7c96c7

File tree

3 files changed

+42
-7
lines changed

3 files changed

+42
-7
lines changed

src/Errors/GraphQLError.php

+39-3
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,16 @@ class GraphQLError extends Exception
1414
protected $node;
1515
protected $path;
1616

17+
protected $customExtensions;
18+
1719
/**
1820
* GraphQLError constructor.
1921
* @param string $message
20-
* @param null $node
21-
* @param null $path
22+
* @param array|null $node
23+
* @param array|null $path
24+
* @param array|null $customExtensions
2225
*/
23-
public function __construct($message = "", $node = null, $path = null)
26+
public function __construct(string $message = "", array $node = null, array $path = null, array $customExtensions=null)
2427
{
2528
parent::__construct($message);
2629
$this->node = $node;
@@ -30,6 +33,7 @@ function ($pathItem) {
3033
return $pathItem !== null;
3134
}
3235
);
36+
$this->customExtensions = $customExtensions;
3337
}
3438

3539
/**
@@ -61,5 +65,37 @@ public function getErrorCode()
6165
{
6266
return $this->code;
6367
}
68+
69+
/**
70+
* @param string $key
71+
* @param mixed $value
72+
* @return $this
73+
*/
74+
public function addCustomExtension(string $key, $value): GraphQLError
75+
{
76+
$this->customExtensions[$key] = $value;
77+
return $this;
78+
}
79+
80+
/**
81+
* Returns all added custom extensions
82+
* @return array
83+
*/
84+
public function getCustomExtensions(): array
85+
{
86+
return $this->customExtensions ?? [];
87+
}
88+
89+
/**
90+
* Returns all extensions of the error.
91+
*
92+
* @return array
93+
*/
94+
public function getExtensions(): array
95+
{
96+
return array_merge([
97+
"code" => $this->getErrorCode()
98+
], $this->getCustomExtensions());
99+
}
64100
}
65101

src/Utilities/Errors.php

+1-3
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@ public static function prettyPrintErrors(array $errors): array
2222
"message" => $error->getMessage(),
2323
"locations" => $error->getLocations(),
2424
"path" => $error->getPath(),
25-
"extensions" => [
26-
"code" => $error->getErrorCode()
27-
]
25+
"extensions" => $error->getExtensions()
2826
];
2927
}, $errors);
3028
}

src/Utilities/LocatedError.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ public static function from(GraphQLError $originalError, $fieldNodes, $path): Gr
2222
return new $errorClassName(
2323
$originalError->getMessage(),
2424
$fieldNodes[0],
25-
$path
25+
$path,
26+
$originalError->getCustomExtensions()
2627
);
2728
}
2829

0 commit comments

Comments
 (0)