Move remaining extension handling to middleware

This commit is contained in:
Franz Liedke 2015-09-09 08:56:11 +02:00
parent afe0eeefc5
commit 37cdc25338
2 changed files with 21 additions and 21 deletions

View File

@ -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);
}
/**

View File

@ -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