From 0c66bd6872576089713701ace677cec79d3d4d05 Mon Sep 17 00:00:00 2001 From: Franz Liedke Date: Sat, 20 Jun 2015 19:45:32 +0200 Subject: [PATCH] Implement middleware for handling errors according to JSON API spec --- .../core/src/Api/Middleware/JsonApiErrors.php | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 framework/core/src/Api/Middleware/JsonApiErrors.php diff --git a/framework/core/src/Api/Middleware/JsonApiErrors.php b/framework/core/src/Api/Middleware/JsonApiErrors.php new file mode 100644 index 000000000..8345b878e --- /dev/null +++ b/framework/core/src/Api/Middleware/JsonApiErrors.php @@ -0,0 +1,36 @@ + $error->getMessage(), + ]; + + $status = 500; + + // If it seems to be a valid HTTP status code, we pass on the + // exception's status. + $errorCode = $error->getCode(); + if (is_int($errorCode) && $errorCode >= 400 && $errorCode < 600) { + $status = $errorCode; + } + + // JSON API errors must be collected in an array under the + // "errors" key in the top level of the document + $data = [ + 'errors' => [$errorObject] + ]; + + return StringResponse::json($data, $status); + } +}