From 134983d13d25c4cc212635ff1171e4e93340adb1 Mon Sep 17 00:00:00 2001 From: shibafu Date: Sat, 8 Aug 2020 15:15:26 +0900 Subject: [PATCH] =?UTF-8?q?JSON=20API=E3=83=AA=E3=82=AF=E3=82=A8=E3=82=B9?= =?UTF-8?q?=E3=83=88=E6=99=82=E3=81=AB=E4=BE=8B=E5=A4=96=E3=81=8C=E7=99=BA?= =?UTF-8?q?=E7=94=9F=E3=81=97=E3=81=9F=E3=82=89=E3=80=81=E5=B8=B8=E3=81=AB?= =?UTF-8?q?JSON=E3=81=A7=E3=83=AC=E3=82=B9=E3=83=9D=E3=83=B3=E3=82=B9?= =?UTF-8?q?=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Exceptions/Handler.php | 27 +++++++++++++++++++++++++++ app/Http/Kernel.php | 1 + app/Http/Middleware/EnforceJson.php | 25 +++++++++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 app/Http/Middleware/EnforceJson.php diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index dcb27e0..c6fd3a8 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -4,7 +4,10 @@ namespace App\Exceptions; use Exception; use Illuminate\Auth\AuthenticationException; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; +use Illuminate\Http\JsonResponse; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class Handler extends ExceptionHandler { @@ -68,4 +71,28 @@ class Handler extends ExceptionHandler return redirect()->guest(route('login')); } + + protected function prepareException(Exception $e) + { + if (!config('app.debug') && $e instanceof ModelNotFoundException) { + return new NotFoundHttpException('Resource not found.', $e); + } + + return parent::prepareException($e); + } + + protected function prepareJsonResponse($request, Exception $e) + { + $status = $this->isHttpException($e) ? $e->getStatusCode() : 500; + + return new JsonResponse( + [ + 'status' => $status, + 'error' => $this->convertExceptionToArray($e), + ], + $status, + $this->isHttpException($e) ? $e->getHeaders() : [], + JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES + ); + } } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 1804b56..927364c 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -40,6 +40,7 @@ class Kernel extends HttpKernel 'api' => [ 'throttle:60,1', + \App\Http\Middleware\EnforceJson::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], diff --git a/app/Http/Middleware/EnforceJson.php b/app/Http/Middleware/EnforceJson.php new file mode 100644 index 0000000..c139bae --- /dev/null +++ b/app/Http/Middleware/EnforceJson.php @@ -0,0 +1,25 @@ +headers->set('Accept', 'application/json'); + + return $next($request); + } +}