From 429b8e1a3254072fa25a510b5b9fbd197b36f94d Mon Sep 17 00:00:00 2001 From: Franz Liedke Date: Wed, 4 Sep 2019 01:44:22 +0200 Subject: [PATCH] Restore error details in JSON-API error formatter Fixes #1865. Refs #1843. --- .../ErrorHandling/JsonApiFormatter.php | 21 ++++++++++----- .../integration/api/users/CreationTest.php | 26 +++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/framework/core/src/Foundation/ErrorHandling/JsonApiFormatter.php b/framework/core/src/Foundation/ErrorHandling/JsonApiFormatter.php index bebdf9d15..4196012e2 100644 --- a/framework/core/src/Foundation/ErrorHandling/JsonApiFormatter.php +++ b/framework/core/src/Foundation/ErrorHandling/JsonApiFormatter.php @@ -26,12 +26,21 @@ class JsonApiFormatter implements HttpFormatter public function format(HandledError $error, Request $request): Response { $document = new Document; - $document->setErrors([ - [ - 'status' => (string) $error->getStatusCode(), - 'code' => $error->getType(), - ], - ]); + + $data = [ + 'status' => (string) $error->getStatusCode(), + 'code' => $error->getType(), + ]; + $details = $error->getDetails(); + + if (empty($details)) { + $document->setErrors([$data]); + } else { + $document->setErrors(array_map( + function ($row) use ($data) { return array_merge($data, $row); }, + $details + )); + } return new JsonApiResponse($document, $error->getStatusCode()); } diff --git a/framework/core/tests/integration/api/users/CreationTest.php b/framework/core/tests/integration/api/users/CreationTest.php index 20963a0a8..4d2bd68a1 100644 --- a/framework/core/tests/integration/api/users/CreationTest.php +++ b/framework/core/tests/integration/api/users/CreationTest.php @@ -58,6 +58,32 @@ class CreationTest extends TestCase ); $this->assertEquals(422, $response->getStatusCode()); + + // The response body should contain details about the failed validation + $body = (string) $response->getBody(); + $this->assertJson($body); + $this->assertEquals([ + 'errors' => [ + [ + 'status' => '422', + 'code' => 'validation_error', + 'detail' => 'validation.required', + 'source' => ['pointer' => '/data/attributes/username'], + ], + [ + 'status' => '422', + 'code' => 'validation_error', + 'detail' => 'validation.required', + 'source' => ['pointer' => '/data/attributes/email'], + ], + [ + 'status' => '422', + 'code' => 'validation_error', + 'detail' => 'validation.required', + 'source' => ['pointer' => '/data/attributes/password'], + ], + ], + ], json_decode($body, true)); } /**