Browse Source

Better exception json response

Bubka 6 years ago
parent
commit
bb4fbfd46e
1 changed files with 35 additions and 5 deletions
  1. 35 5
      app/Exceptions/Handler.php

+ 35 - 5
app/Exceptions/Handler.php

@@ -5,6 +5,8 @@ namespace App\Exceptions;
 use Exception;
 use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
 use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
+use Illuminate\Validation\ValidationException as ValidationException;
+use Symfony\Component\HttpKernel\Exception\HttpException;
 
 class Handler extends ExceptionHandler
 {
@@ -47,13 +49,41 @@ class Handler extends ExceptionHandler
      */
     public function render($request, Exception $exception)
     {
-        if ($exception instanceof ModelNotFoundException)
-        {
-            return response()->json([
-                'message' => 'Resource not found',
-            ], 404);
+        if (!($exception instanceof ValidationException)) {
+            $response = [
+                'message' => (string)$exception->getMessage(),
+                'status_code' => 400,
+            ];
+
+            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);
     }
+
+    /**
+     * Determine if the application is in debug mode.
+     *
+     * @return Boolean
+     */
+    public function isDebugMode()
+    {
+        return (boolean) env('APP_DEBUG');
+    }
 }