22
33namespace GemaDigital \Exceptions ;
44
5+ use Exception ;
6+ use Illuminate \Auth \AuthenticationException ;
57use Illuminate \Foundation \Configuration \Exceptions ;
68use Illuminate \Http \Request ;
9+ use Illuminate \Http \Response ;
710use Throwable ;
811
912class ExceptionHandler
@@ -13,15 +16,23 @@ public static function handle(Exceptions $exceptions): void
1316 $ exceptions ->render (self ::render (...));
1417 }
1518
16- /** @phpstan-ignore-next-line */
17- public static function render (Throwable $ exception , Request $ request )
19+ /**
20+ * Render an exception into an HTTP json response.
21+ */
22+ public static function render (Throwable $ exception , Request $ request ): Response |false
1823 {
19- if ($ request ->expectsJson ()) {
24+ if (app ()-> hasDebugModeEnabled () && $ request ->expectsJson ()) {
2025 $ name = basename ($ exception ::class);
2126 $ file = preg_replace ('/ \\\/ ' , '/ ' , str_replace (base_path (), '' , $ exception ->getFile ()));
2227 $ message = htmlspecialchars ($ exception ->getMessage ());
2328 $ errors = method_exists ($ exception , 'errors ' ) ? $ exception ->errors () : ['exception ' => $ message ];
24- $ code = method_exists ($ exception , 'getStatusCode ' ) ? $ exception ->getStatusCode () : 400 ;
29+ $ code = method_exists ($ exception , 'getStatusCode ' ) ? $ exception ->getStatusCode () : null ;
30+
31+ $ code ??= match ($ exception ::class) {
32+ AuthenticationException::class => 401 ,
33+ Exception::class => $ exception ->getCode (),
34+ default => 400 ,
35+ };
2536
2637 return response ()->api (null , -1 , $ code , $ errors , [
2738 $ name => [
@@ -32,5 +43,7 @@ public static function render(Throwable $exception, Request $request)
3243 ],
3344 ]);
3445 }
46+
47+ return false ;
3548 }
3649}
0 commit comments