aiblog/app/Exceptions/Handler.php
2024-11-17 11:30:01 +08:00

82 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Auth\Access\AuthorizationException;
use Throwable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->renderable(function (AuthenticationException $e) {
return response()->json([
'error' => 'Unauthenticated',
'message' => 'You must be logged in to access this resource.',
], 401);
});
$this->renderable(function (ValidationException $e) {
return response()->json([
'error' => 'Validation Error',
'message' => 'The given data was invalid.',
'errors' => $e->errors(),
], 422);
});
$this->renderable(function (NotFoundHttpException $e) {
return response()->json([
'error' => 'Not Found',
'message' => 'The requested resource was not found.',
], 404);
});
$this->renderable(function (AuthorizationException $e) {
return response()->json([
'error' => 'Forbidden',
'message' => 'You are not authorized to perform this action.',
], 403);
});
$this->renderable(function (Throwable $e) {
if (config('app.debug')) {
throw $e;
}
return response()->json([
'error' => 'Server Error',
'message' => 'An unexpected error occurred.',
], 500);
});
$this->renderable(function (ModelNotFoundException $e) {
return response()->error('Resource not found', 404);
});
$this->renderable(function (QueryException $e) {
return response()->error('Database error', 500);
});
}
}