mirror of
https://github.com/flarum/framework.git
synced 2025-02-22 06:27:57 +08:00
Implement middleware for handling errors according to JSON API spec
This commit is contained in:
parent
3a0103de7b
commit
0c66bd6872
36
framework/core/src/Api/Middleware/JsonApiErrors.php
Normal file
36
framework/core/src/Api/Middleware/JsonApiErrors.php
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
<?php namespace Flarum\Api\Middleware;
|
||||||
|
|
||||||
|
use Psr\Http\Message\ResponseInterface as Response;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||||
|
use Zend\Diactoros\Response\StringResponse;
|
||||||
|
use Zend\Stratigility\ErrorMiddlewareInterface;
|
||||||
|
|
||||||
|
class JsonApiErrors implements ErrorMiddlewareInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function __invoke($error, Request $request, Response $response, callable $out = null)
|
||||||
|
{
|
||||||
|
$errorObject = [
|
||||||
|
'title' => $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);
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user