store-manage/app/Exceptions/Handler.php

84 lines
2.7 KiB
PHP

<?php
namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Slowlyo\OwlAdmin\Exceptions\AdminException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
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',
];
protected $dontReport = [
AdminException::class,
RuntimeException::class,
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->map(ModelNotFoundException::class, function (ModelNotFoundException $e) {
$model = $e->getModel();
$resource = __($key = "model.{$model}");
if ($key === $resource) {
$resource = class_basename($model);
}
return new HttpException(404, __(':resource not found', ['resource' => $resource]), $e);
});
$this->renderable(function (RuntimeException $e, Request $request) {
return response(['code' => $e->getCode(), 'message' => $e->getMessage()], $e->getHttpStatusCode());
});
$this->renderable(function (NotFoundHttpException $e, Request $request) {
return response(['code' => Response::HTTP_NOT_FOUND, 'message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
});
$this->reportable(function (NoGatewayAvailableException $e) {
foreach ($e->getExceptions() as $exception) {
$this->report($exception);
}
return false;
});
}
protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'code' => $exception->status,
'message' => $exception->getMessage(),
'errors' => $exception->errors(),
], $exception->status);
}
protected function unauthenticated($request, AuthenticationException $exception)
{
return $this->shouldReturnJson($request, $exception)
? response()->json(['code' => Response::HTTP_UNAUTHORIZED, 'message' => '请先登录'], 401)
: redirect()->guest($exception->redirectTo() ?? url('/'));
}
}