Просмотр исходного кода

add custom api exception response

Yong 2 лет назад
Родитель
Сommit
18a00f2d57
1 измененных файлов: 99 добавлений и 1 удалений
  1. 99
    1
      app/Exceptions/Handler.php

+ 99
- 1
app/Exceptions/Handler.php Просмотреть файл

@@ -2,8 +2,18 @@
2 2
 
3 3
 namespace App\Exceptions;
4 4
 
5
-use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
6 5
 use Throwable;
6
+use Illuminate\Http\Response;
7
+use Illuminate\Support\Facades\Log;
8
+use Illuminate\Database\QueryException;
9
+use Illuminate\Auth\AuthenticationException;
10
+use Illuminate\Validation\ValidationException;
11
+use Illuminate\Database\Eloquent\ModelNotFoundException;
12
+use Symfony\Component\HttpKernel\Exception\HttpException;
13
+use Symfony\Component\Routing\Exception\RouteNotFoundException;
14
+use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
15
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
16
+use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
7 17
 
8 18
 class Handler extends ExceptionHandler
9 19
 {
@@ -37,5 +47,93 @@ class Handler extends ExceptionHandler
37 47
         $this->reportable(function (Throwable $e) {
38 48
             //
39 49
         });
50
+
51
+        $this->renderable(function (Throwable $e, $request) {
52
+            return $this->handleException($request, $e);
53
+        });
54
+    }
55
+
56
+    public function handleException($request, Throwable $exception)
57
+    {
58
+        // Route Not Found
59
+        if ($exception instanceof RouteNotFoundException) {
60
+            return $this->exceptionResponse($request, $exception, Response::HTTP_NOT_FOUND, config('response-message.router_failed'));
61
+        }
62
+
63
+        // Not Found
64
+        if ($exception instanceof NotFoundHttpException) {
65
+            $message = $exception->getMessage() ?? config('response-message.not_found');
66
+            return $this->exceptionResponse($request, $exception, Response::HTTP_NOT_FOUND, $message);
67
+        }
68
+
69
+        // Model Not Found
70
+        if ($exception instanceof ModelNotFoundException) {
71
+            $exception = new NotFoundHttpException($exception->getMessage(), $exception);
72
+        }
73
+
74
+        // Authentication
75
+        if ($exception instanceof AuthenticationException) {
76
+            return $this->exceptionResponse($request, $exception, Response::HTTP_UNAUTHORIZED, config('response-message.authenticate_failed'));
77
+        }
78
+
79
+        // Unauthorized
80
+        if ($exception instanceof UnauthorizedHttpException) {
81
+            return $this->exceptionResponse($request, $exception, $exception->getStatusCode(), config('response-message.authorize_failed'));
82
+        }
83
+
84
+        // Http
85
+        if ($exception instanceof HttpException) {
86
+            return $this->exceptionResponse($request, $exception, $exception->getStatusCode(), $exception->getMessage());
87
+        }
88
+
89
+        // Query
90
+        if ($exception instanceof QueryException) {
91
+            $this->exceptionResponse($request, $exception, Response::HTTP_INTERNAL_SERVER_ERROR, config('response-message.sql_error'));
92
+        }
93
+
94
+        // Validation
95
+        if ($exception instanceof ValidationException) {
96
+
97
+            if (!$request->is('api/*')) {
98
+                return $this->convertValidationExceptionToResponse($exception, $request);
99
+            }
100
+
101
+            $validationData = [];
102
+            foreach ($exception->errors() as $key => $item) {
103
+                $validationData['errors']['validation'][$key] = $item[0];
104
+            }
105
+            return $this->exceptionResponse($request, $exception, Response::HTTP_UNPROCESSABLE_ENTITY, config('response-message.validation_failed'), $validationData);
106
+        }
107
+
108
+        // Others
109
+        return $this->exceptionResponse($request, $exception, Response::HTTP_INTERNAL_SERVER_ERROR, 'server error');
110
+    }
111
+
112
+    public function exceptionResponse($request, $exception, $code, $message, $mergeData = [])
113
+    {
114
+        if ($code === Response::HTTP_INTERNAL_SERVER_ERROR) {
115
+            Log::info($exception->getMessage());
116
+        }
117
+
118
+
119
+        if ($request->is('api/*')) {
120
+            $data = [
121
+                'code'    => $code,
122
+                'message' => $message,
123
+            ];
124
+
125
+            if (!app()->environment('production')) {
126
+                $data['errors'] = [
127
+                    'message' => $exception->getMessage(),
128
+                    'trace'   => $exception->getTrace(),
129
+                ];
130
+            }
131
+
132
+            if (!empty($mergeData)) {
133
+                $data = array_merge($data, $mergeData);
134
+            }
135
+
136
+            return response()->json($data, $code);
137
+        }
40 138
     }
41 139
 }