Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a316105

Browse files
authored
feat: throw better exception for empty request body (GoogleCloudPlatform#35)
1 parent 40f2d30 commit a316105

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

src/BackgroundFunctionWrapper.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,13 @@ public function __construct(callable $function)
3131

3232
public function execute(ServerRequestInterface $request): ResponseInterface
3333
{
34-
$event = json_decode((string) $request->getBody(), true);
34+
$body = (string) $request->getBody();
35+
$event = json_decode($body, true);
3536
if (json_last_error() != JSON_ERROR_NONE) {
36-
throw new RuntimeException('Could not parse request body: ' . json_last_error_msg());
37+
throw new RuntimeException(sprintf(
38+
'Could not parse request body: %s',
39+
'' !== $body ? json_last_error_msg() : 'Missing event payload'
40+
));
3741
}
3842

3943
$data = $event['data'];

tests/BackgroundFunctionWrapperTest.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,19 @@ class BackgroundFunctionWrapperTest extends TestCase
3232
public function testInvalidRequestBody()
3333
{
3434
$this->expectException('RuntimeException');
35-
$this->expectExceptionMessage('Could not parse request body');
35+
$this->expectExceptionMessage('Could not parse request body: Syntax error');
36+
$request = new ServerRequest('GET', '/', [], 'notjson');
3637
$backgroundFunctionWrapper = new BackgroundFunctionWrapper([$this, 'invokeThis']);
37-
$backgroundFunctionWrapper->execute(new ServerRequest('GET', '/'));
38+
$backgroundFunctionWrapper->execute($request);
39+
}
40+
41+
public function testEmptyRequestBody()
42+
{
43+
$this->expectException('RuntimeException');
44+
$this->expectExceptionMessage('Could not parse request body: Missing event payload');
45+
$request = new ServerRequest('GET', '/', [], '');
46+
$backgroundFunctionWrapper = new BackgroundFunctionWrapper([$this, 'invokeThis']);
47+
$backgroundFunctionWrapper->execute($request);
3848
}
3949

4050
public function testHttpBackgroundFunctionWrapper()

0 commit comments

Comments
 (0)