Better exception json response

This commit is contained in:
Bubka 2019-05-26 16:44:46 +02:00
parent 6a76a493a2
commit bb4fbfd46e

View File

@ -5,6 +5,8 @@
use Exception; use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
use Illuminate\Validation\ValidationException as ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
{ {
@ -47,13 +49,41 @@ public function report(Exception $exception)
*/ */
public function render($request, Exception $exception) public function render($request, Exception $exception)
{ {
if ($exception instanceof ModelNotFoundException) if (!($exception instanceof ValidationException)) {
{ $response = [
return response()->json([ 'message' => (string)$exception->getMessage(),
'message' => 'Resource not found', 'status_code' => 400,
], 404); ];
if ($exception instanceof HttpException) {
$response['message'] = Response::$statusTexts[$exception->getStatusCode()];
$response['status_code'] = $exception->getStatusCode();
} else if ($exception instanceof ModelNotFoundException) {
$response['message'] = Response::$statusTexts[Response::HTTP_NOT_FOUND];
$response['status_code'] = Response::HTTP_NOT_FOUND;
}
if ($this->isDebugMode()) {
$response['debug'] = [
'exception' => get_class($exception),
'trace' => $exception->getTrace()
];
// return parent::render($request, $exception);
}
return response()->json($response, $response['status_code']);
} }
return parent::render($request, $exception); return parent::render($request, $exception);
} }
/**
* Determine if the application is in debug mode.
*
* @return Boolean
*/
public function isDebugMode()
{
return (boolean) env('APP_DEBUG');
}
} }