mirror of
https://github.com/flarum/core.git
synced 2025-10-13 07:54:25 +02:00
Improve API error handling
- Change 'path' key to 'source.pointer', as per spec - Add 500 error detail if debug mode is on
This commit is contained in:
@@ -17,45 +17,52 @@ use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
use Zend\Stratigility\ErrorMiddlewareInterface;
|
||||
use Flarum\Core;
|
||||
use Exception;
|
||||
|
||||
class JsonApiErrors implements ErrorMiddlewareInterface
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __invoke($error, Request $request, Response $response, callable $out = null)
|
||||
public function __invoke($e, Request $request, Response $response, callable $out = null)
|
||||
{
|
||||
if ($error instanceof JsonApiSerializable) {
|
||||
$status = $error->getStatusCode();
|
||||
return $this->handle($e);
|
||||
}
|
||||
|
||||
$errors = $error->getErrors();
|
||||
} else if ($error instanceof ValidationException) {
|
||||
public function handle(Exception $e)
|
||||
{
|
||||
if ($e instanceof JsonApiSerializable) {
|
||||
$status = $e->getStatusCode();
|
||||
|
||||
$errors = $e->getErrors();
|
||||
} else if ($e instanceof ValidationException) {
|
||||
$status = 422;
|
||||
|
||||
$errors = $error->errors()->toArray();
|
||||
$errors = $e->errors()->toArray();
|
||||
$errors = array_map(function ($field, $messages) {
|
||||
return [
|
||||
'detail' => implode("\n", $messages),
|
||||
'path' => $field,
|
||||
'source' => ['pointer' => '/data/attributes/' . $field],
|
||||
];
|
||||
}, array_keys($errors), $errors);
|
||||
} else if ($error instanceof ModelNotFoundException) {
|
||||
} else if ($e instanceof ModelNotFoundException) {
|
||||
$status = 404;
|
||||
|
||||
$errors = [];
|
||||
} else {
|
||||
$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;
|
||||
$error = [
|
||||
'code' => $status,
|
||||
'title' => 'Internal Server Error'
|
||||
];
|
||||
|
||||
if (Core::inDebugMode()) {
|
||||
$error['detail'] = (string) $e;
|
||||
}
|
||||
|
||||
$errors = [
|
||||
['title' => $error->getMessage()]
|
||||
];
|
||||
$errors = [$error];
|
||||
}
|
||||
|
||||
// JSON API errors must be collected in an array under the
|
||||
|
Reference in New Issue
Block a user