77use Illuminate \Auth \AuthenticationException ;
88use Illuminate \Database \Eloquent \ModelNotFoundException ;
99use Illuminate \Foundation \Exceptions \Handler as ExceptionHandler ;
10+ use Illuminate \Http \JsonResponse ;
11+ use Illuminate \Http \Request ;
12+ use Illuminate \Http \Response ;
1013use Illuminate \Validation \ValidationException ;
1114use Symfony \Component \HttpKernel \Exception \HttpException ;
1215use Symfony \Component \HttpKernel \Exception \NotFoundHttpException ;
@@ -47,6 +50,10 @@ public function report(Exception $e)
4750 */
4851 public function render ($ request , Exception $ e )
4952 {
53+ if ($ this ->isApiRequest ($ request )) {
54+ return $ this ->renderApiException ($ e );
55+ }
56+
5057 // Handle notify exceptions which will redirect to the
5158 // specified location then show a notification message.
5259 if ($ this ->isExceptionType ($ e , NotifyException::class)) {
@@ -70,6 +77,41 @@ public function render($request, Exception $e)
7077 return parent ::render ($ request , $ e );
7178 }
7279
80+ /**
81+ * Check if the given request is an API request.
82+ */
83+ protected function isApiRequest (Request $ request ): bool
84+ {
85+ return strpos ($ request ->path (), 'api/ ' ) === 0 ;
86+ }
87+
88+ /**
89+ * Render an exception when the API is in use.
90+ */
91+ protected function renderApiException (Exception $ e ): JsonResponse
92+ {
93+ $ code = $ e ->getCode () === 0 ? 500 : $ e ->getCode ();
94+ $ headers = [];
95+ if ($ e instanceof HttpException) {
96+ $ code = $ e ->getStatusCode ();
97+ $ headers = $ e ->getHeaders ();
98+ }
99+
100+ $ responseData = [
101+ 'error ' => [
102+ 'message ' => $ e ->getMessage (),
103+ ]
104+ ];
105+
106+ if ($ e instanceof ValidationException) {
107+ $ responseData ['error ' ]['validation ' ] = $ e ->errors ();
108+ $ code = $ e ->status ;
109+ }
110+
111+ $ responseData ['error ' ]['code ' ] = $ code ;
112+ return new JsonResponse ($ responseData , $ code , $ headers );
113+ }
114+
73115 /**
74116 * Check the exception chain to compare against the original exception type.
75117 * @param Exception $e
0 commit comments