From 3c6010679a927db2e24e82bdcfb55ae551e58658 Mon Sep 17 00:00:00 2001 From: snipe Date: Thu, 12 Jan 2017 19:06:39 -0800 Subject: [PATCH] Nicer handler for JSON model not found errors --- app/Exceptions/Handler.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index c73877e247..f0a0c8f1b8 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -5,6 +5,7 @@ namespace App\Exceptions; use Exception; use Illuminate\Auth\AuthenticationException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; +use App\Helpers\Helper; class Handler extends ExceptionHandler { @@ -44,17 +45,36 @@ class Handler extends ExceptionHandler */ public function render($request, Exception $e) { + + + // CSRF token mismatch error if ($e instanceof \Illuminate\Session\TokenMismatchException) { return redirect()->back()->with('error', trans('general.token_expired')); } + + // Handle Ajax requests that fail because the model doesn't exist + if ($request->ajax() || $request->wantsJson()) { + if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { + $className = last(explode('\\', $e->getModel())); + return response()->json(Helper::formatStandardApiResponse('error', null, $className . ' not found'), 200); + } + } + + if ($this->isHttpException($e)) { + $statusCode = $e->getStatusCode(); switch ($statusCode) { case '404': + if ($request->ajax() || $request->wantsJson()) + { + return response()->json(Helper::formatStandardApiResponse('error', null, $statusCode . ' not found'), 404); + } + return response()->view('layouts/basic', [ 'content' => view('errors/404') ]);