More work on the API utilizing Laravel 5.5 exception rendering

Also corrects API format to maintain JSONAPI spec
This commit is contained in:
Dane Everitt 2017-12-17 14:57:05 -06:00
parent f30f4b45ba
commit 54b6fb5ebd
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
28 changed files with 464 additions and 391 deletions

View file

@ -11,9 +11,12 @@ namespace Pterodactyl\Exceptions;
use Log;
use Throwable;
use Prologue\Alerts\AlertsMessageBag;
class DisplayException extends PterodactylException
{
const LEVEL_DEBUG = 'debug';
const LEVEL_INFO = 'info';
const LEVEL_WARNING = 'warning';
const LEVEL_ERROR = 'error';
@ -32,13 +35,13 @@ class DisplayException extends PterodactylException
*/
public function __construct($message, Throwable $previous = null, $level = self::LEVEL_ERROR, $code = 0)
{
$this->level = $level;
parent::__construct($message, $code, $previous);
if (! is_null($previous)) {
Log::{$level}($previous);
}
parent::__construct($message, $code, $previous);
$this->level = $level;
}
/**
@ -48,4 +51,25 @@ class DisplayException extends PterodactylException
{
return $this->level;
}
/**
* Render the exception to the user by adding a flashed message to the session
* and then redirecting them back to the page that they came from. If the
* request originated from an API hit, return the error in JSONAPI spec format.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
*/
public function render($request)
{
if ($request->expectsJson()) {
return response()->json(Handler::convertToArray($this, [
'detail' => $this->getMessage(),
]), 500);
}
app()->make(AlertsMessageBag::class)->danger($this->getMessage())->flash();
return redirect()->back()->withInput();
}
}

View file

@ -1,14 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Exceptions;
class DisplayValidationException extends DisplayException
{
}

View file

@ -3,13 +3,11 @@
namespace Pterodactyl\Exceptions;
use Exception;
use Prologue\Alerts\Facades\Alert;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Pterodactyl\Exceptions\Model\DataValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
@ -25,8 +23,6 @@ class Handler extends ExceptionHandler
AuthenticationException::class,
AuthorizationException::class,
DisplayException::class,
DataValidationException::class,
DisplayValidationException::class,
HttpException::class,
ModelNotFoundException::class,
RecordNotFoundException::class,
@ -34,6 +30,16 @@ class Handler extends ExceptionHandler
ValidationException::class,
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
@ -53,41 +59,78 @@ class Handler extends ExceptionHandler
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Exception
*/
public function render($request, Exception $exception)
{
if ($request->expectsJson() || $request->isJson() || $request->is(...config('pterodactyl.json_routes'))) {
$exception = $this->prepareException($exception);
return parent::render($request, $exception);
}
if (config('app.debug') || $this->isHttpException($exception) || $exception instanceof DisplayException) {
$displayError = $exception->getMessage();
} else {
$displayError = 'An unhandled exception was encountered with this request.';
/**
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
public function invalidJson($request, ValidationException $exception)
{
$codes = collect($exception->validator->failed())->mapWithKeys(function ($reasons, $field) {
$cleaned = [];
foreach ($reasons as $reason => $attrs) {
$cleaned[] = snake_case($reason);
}
$response = response()->json(
[
'error' => $displayError,
'type' => (! config('app.debug')) ? null : class_basename($exception),
'http_code' => (method_exists($exception, 'getStatusCode')) ? $exception->getStatusCode() : 500,
'trace' => (! config('app.debug')) ? null : $exception->getTrace(),
return [$field => $cleaned];
})->toArray();
$errors = collect($exception->errors())->map(function ($errors, $field) use ($codes) {
$response = [];
foreach ($errors as $key => $error) {
$response[] = [
'code' => array_get($codes, $field . '.' . $key),
'detail' => $error,
'source' => ['field' => $field],
];
}
return $response;
})->flatMap(function ($errors) {
return $errors;
})->toArray();
return response()->json(['errors' => $errors], $exception->status);
}
/**
* Return the exception as a JSONAPI representation for use on API requests.
*
* @param \Exception $exception
* @param array $override
* @return array
*/
public static function convertToArray(Exception $exception, array $override = []): array
{
$error = [
'code' => class_basename($exception),
'status' => method_exists($exception, 'getStatusCode') ? strval($exception->getStatusCode()) : '500',
'detail' => 'An error was encountered while processing this request.',
];
if (config('app.debug')) {
$error = array_merge($error, [
'detail' => $exception->getMessage(),
'source' => [
'line' => $exception->getLine(),
'file' => str_replace(base_path(), '', $exception->getFile()),
],
$this->isHttpException($exception) ? $exception->getStatusCode() : 500,
$this->isHttpException($exception) ? $exception->getHeaders() : [],
JSON_UNESCAPED_SLASHES
);
parent::report($exception);
} elseif ($exception instanceof DisplayException) {
Alert::danger($exception->getMessage())->flash();
return redirect()->back()->withInput();
'meta' => [
'trace' => explode("\n", $exception->getTraceAsString()),
],
]);
}
return (isset($response)) ? $response : parent::render($request, $exception);
return ['errors' => [array_merge($error, $override)]];
}
/**
@ -105,4 +148,16 @@ class Handler extends ExceptionHandler
return redirect()->guest(route('auth.login'));
}
/**
* Converts an exception into an array to render in the response. Overrides
* Laravel's built-in converter to output as a JSONAPI spec compliant object.
*
* @param \Exception $exception
* @return array
*/
protected function convertExceptionToArray(Exception $exception)
{
return self::convertToArray($exception);
}
}

View file

@ -1,20 +1,21 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Exceptions\Model;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Exceptions\PterodactylException;
use Illuminate\Contracts\Support\MessageProvider;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class DataValidationException extends ValidationException implements MessageProvider
class DataValidationException extends PterodactylException implements HttpExceptionInterface, MessageProvider
{
/**
* The validator instance.
*
* @var \Illuminate\Contracts\Validation\Validator
*/
public $validator;
/**
* DataValidationException constructor.
*
@ -22,14 +23,38 @@ class DataValidationException extends ValidationException implements MessageProv
*/
public function __construct(Validator $validator)
{
parent::__construct($validator);
parent::__construct(
'Data integrity exception encountered while performing database write operation. ' . $validator->errors()->toJson()
);
$this->validator = $validator;
}
/**
* Return the validator message bag.
*
* @return \Illuminate\Support\MessageBag
*/
public function getMessageBag()
{
return $this->validator->errors();
}
/**
* Return the status code for this request.
*
* @return int
*/
public function getStatusCode()
{
return 500;
}
/**
* @return array
*/
public function getHeaders()
{
return [];
}
}

View file

@ -1,11 +1,4 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Exceptions;

View file

@ -1,14 +1,9 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Exceptions\Repository\Daemon;
class InvalidPowerSignalException extends \Exception
use Pterodactyl\Exceptions\Repository\RepositoryException;
class InvalidPowerSignalException extends RepositoryException
{
}

View file

@ -1,11 +1,4 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Exceptions\Repository;

View file

@ -1,21 +1,20 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Exceptions\Repository;
class RecordNotFoundException extends \Exception
class RecordNotFoundException extends RepositoryException
{
/**
* @return int
* Handle request to render this exception to a user. Returns the default
* 404 page view.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function getStatusCode()
public function render($request)
{
return 404;
if (! config('app.debug')) {
return response()->view('errors.404', [], 404);
}
}
}

View file

@ -1,14 +1,9 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Exceptions\Repository;
class RepositoryException extends \Exception
use Pterodactyl\Exceptions\PterodactylException;
class RepositoryException extends PterodactylException
{
}