Skip to content

Commit

Permalink
Move remaining extension handling to middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
franzliedke committed Sep 9, 2015
1 parent b8ac49f commit 502a378
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 21 deletions.
18 changes: 1 addition & 17 deletions src/Api/Actions/JsonApiAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}

/**
Expand Down
24 changes: 20 additions & 4 deletions src/Api/Middleware/JsonApiErrors.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -27,19 +29,33 @@ public function __invoke($error, Request $request, Response $response, callable
$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
Expand Down

0 comments on commit 502a378

Please sign in to comment.