mirror of
https://github.com/flarum/framework.git
synced 2024-12-05 09:03:36 +08:00
Move remaining extension handling to middleware
This commit is contained in:
parent
afe0eeefc5
commit
37cdc25338
|
@ -11,8 +11,6 @@
|
|||
namespace Flarum\Api\Actions;
|
||||
|
||||
use Flarum\Api\Request;
|
||||
use Illuminate\Contracts\Validation\ValidationException;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
abstract class JsonApiAction implements Action
|
||||
|
@ -26,21 +24,7 @@ abstract class JsonApiAction implements Action
|
|||
*/
|
||||
public function handle(Request $request)
|
||||
{
|
||||
// TODO: This is gross. Move this error handling code to middleware?
|
||||
try {
|
||||
return $this->respond($request);
|
||||
} catch (ValidationException $e) {
|
||||
$errors = [];
|
||||
foreach ($e->errors()->toArray() as $field => $messages) {
|
||||
$errors[] = [
|
||||
'detail' => implode("\n", $messages),
|
||||
'path' => $field
|
||||
];
|
||||
}
|
||||
return new JsonResponse(['errors' => $errors], 422);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return new JsonResponse(null, 404);
|
||||
}
|
||||
return $this->respond($request);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -11,6 +11,8 @@
|
|||
namespace Flarum\Api\Middleware;
|
||||
|
||||
use Flarum\Core\Exceptions\JsonApiSerializable;
|
||||
use Illuminate\Contracts\Validation\ValidationException;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
@ -27,19 +29,33 @@ class JsonApiErrors implements ErrorMiddlewareInterface
|
|||
$status = $error->getStatusCode();
|
||||
|
||||
$errors = $error->getErrors();
|
||||
} else if ($error instanceof ValidationException) {
|
||||
$status = 422;
|
||||
|
||||
$errors = $error->errors()->toArray();
|
||||
$errors = array_map(function ($field, $messages) {
|
||||
return [
|
||||
'detail' => implode("\n", $messages),
|
||||
'path' => $field,
|
||||
];
|
||||
}, array_keys($errors), $errors);
|
||||
} else if ($error instanceof ModelNotFoundException) {
|
||||
$status = 404;
|
||||
|
||||
$errors = [];
|
||||
} else {
|
||||
$status = 500;
|
||||
|
||||
$errors = [
|
||||
['title' => $error->getMessage()]
|
||||
];
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
$errors = [
|
||||
['title' => $error->getMessage()]
|
||||
];
|
||||
}
|
||||
|
||||
// JSON API errors must be collected in an array under the
|
||||
|
|
Loading…
Reference in New Issue
Block a user