Skip to content

Commit 870528c

Browse files
committed
fix: Improve exception handling in ExceptionHandler class
1 parent e36c15e commit 870528c

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

src/app/Exceptions/ExceptionHandler.php

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22

33
namespace GemaDigital\Exceptions;
44

5+
use Exception;
6+
use Illuminate\Auth\AuthenticationException;
57
use Illuminate\Foundation\Configuration\Exceptions;
68
use Illuminate\Http\Request;
9+
use Illuminate\Http\Response;
710
use Throwable;
811

912
class 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

Comments
 (0)