Skip to content

Commit

Permalink
Move exception handling for Flarum exception classes to middleware
Browse files Browse the repository at this point in the history
Related to #118.
  • Loading branch information
franzliedke committed Sep 8, 2015
1 parent 4b4cea4 commit b8ac49f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 20 deletions.
10 changes: 0 additions & 10 deletions src/Api/Actions/JsonApiAction.php
Expand Up @@ -13,8 +13,6 @@
use Flarum\Api\Request;
use Illuminate\Contracts\Validation\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Flarum\Core\Exceptions\ValidationFailureException;
use Flarum\Core\Exceptions\PermissionDeniedException;
use Zend\Diactoros\Response\JsonResponse;

abstract class JsonApiAction implements Action
Expand All @@ -40,14 +38,6 @@ public function handle(Request $request)
];
}
return new JsonResponse(['errors' => $errors], 422);
} catch (\Flarum\Core\Exceptions\ValidationException $e) {
$errors = [];
foreach ($e->getMessages() as $path => $detail) {
$errors[] = compact('path', 'detail');
}
return new JsonResponse(['errors' => $errors], 422);
} catch (PermissionDeniedException $e) {
return new JsonResponse(null, 401);
} catch (ModelNotFoundException $e) {
return new JsonResponse(null, 404);
}
Expand Down
27 changes: 17 additions & 10 deletions src/Api/Middleware/JsonApiErrors.php
Expand Up @@ -10,6 +10,7 @@

namespace Flarum\Api\Middleware;

use Flarum\Core\Exceptions\JsonApiSerializable;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Response\JsonResponse;
Expand All @@ -22,23 +23,29 @@ class JsonApiErrors implements ErrorMiddlewareInterface
*/
public function __invoke($error, Request $request, Response $response, callable $out = null)
{
$errorObject = [
'title' => $error->getMessage(),
];
if ($error instanceof JsonApiSerializable) {
$status = $error->getStatusCode();

$errors = $error->getErrors();
} else {
$status = 500;

$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;
// 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]
'errors' => $errors,
];

return new JsonResponse($data, $status);
Expand Down

0 comments on commit b8ac49f

Please sign in to comment.