Skip to content

Commit 2786b9a

Browse files
committed
Fixing exception code => HTTP code
1 parent 78d576e commit 2786b9a

File tree

3 files changed

+12
-7
lines changed

3 files changed

+12
-7
lines changed

Controller/GraphqliteController.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,14 +128,15 @@ private function decideHttpStatusCode(ExecutionResult $result): int
128128
$status = 0;
129129
// There might be many errors. Let's return the highest code we encounter.
130130
foreach ($result->errors as $error) {
131-
if ($error->getCategory() === Error::CATEGORY_GRAPHQL) {
132-
$code = 400;
133-
} else {
134-
$code = $error->getCode();
131+
$wrappedException = $error->getPrevious();
132+
if ($wrappedException !== null) {
133+
$code = $wrappedException->getCode();
135134
if (!isset(Response::$statusTexts[$code])) {
136135
// The exception code is not a valid HTTP code. Let's ignore it
137136
continue;
138137
}
138+
} else {
139+
$code = 400;
139140
}
140141
$status = max($status, $code);
141142
}

Tests/Fixtures/Controller/TestGraphqlController.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
namespace TheCodingMachine\Graphqlite\Bundle\Tests\Fixtures\Controller;
55

66

7+
use GraphQL\Error\Error;
78
use Porpaginas\Arrays\ArrayResult;
89
use TheCodingMachine\Graphqlite\Bundle\Tests\Fixtures\Entities\Contact;
910
use TheCodingMachine\Graphqlite\Bundle\Tests\Fixtures\Entities\Product;
@@ -61,7 +62,7 @@ public function contacts(): ArrayResult
6162
* @Query()
6263
* @return string
6364
*/
64-
public function triggerError(int $code = 500): string
65+
public function triggerException(int $code = 500): string
6566
{
6667
throw new MyException('Boom', $code);
6768
}

Tests/FunctionalTest.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,16 +106,19 @@ public function testErrors()
106106

107107
$request = Request::create('/graphql', 'GET', ['query' => '
108108
{
109-
triggerError
109+
triggerException
110110
}']);
111111

112112
$response = $kernel->handle($request);
113113

114114
$this->assertSame(500, $response->getStatusCode());
115115

116+
// Let's test that the highest exception code compatible with an HTTP is kept.
116117
$request = Request::create('/graphql', 'GET', ['query' => '
117118
{
118-
triggerError(code: 404)
119+
triggerError1: triggerException(code: 404)
120+
triggerError2: triggerException(code: 401)
121+
triggerError3: triggerException(code: 10245)
119122
}']);
120123

121124
$response = $kernel->handle($request);

0 commit comments

Comments
 (0)