123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <?php
- namespace App\Exceptions;
- use Illuminate\Auth\AuthenticationException;
- use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
- use Illuminate\Support\Facades\Log;
- use Throwable;
- use Illuminate\Validation\ValidationException;
- use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
- use Symfony\Component\Routing\Exception\RouteNotFoundException;
- class Handler extends ExceptionHandler
- {
- /**
- * A list of the exception types that are not reported.
- *
- * @var array<int, class-string<Throwable>>
- */
- protected $dontReport = [
- //
- ];
- /**
- * A list of the inputs that are never flashed for validation exceptions.
- *
- * @var array<int, string>
- */
- protected $dontFlash = [
- 'current_password',
- 'password',
- 'password_confirmation',
- ];
- /**
- * Register the exception handling callbacks for the application.
- *
- * @return void
- */
- public function register()
- {
- $this->reportable(function (Throwable $e) {
- //
- });
- }
- // 异常处理
- public function report(Throwable $exception)
- {
- parent::report($exception); // 调用父类的 report 方法,记录日志
- }
- /**
- * Render an exception into an HTTP response.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Throwable $exception
- * @return \Symfony\Component\HttpFoundation\Response
- */
- public function render($request, Throwable $exception)
- {
- // sanctum 异常处理
- if ($exception instanceof RouteNotFoundException || $exception instanceof AuthenticationException) {
- return response()->json([
- 'code' => 401,
- 'msg' => "登录已过期",
- ], 401);
- }
- // 捕获 NotFoundHttpException 异常并自定义处理
- if ($exception instanceof NotFoundHttpException) {
- return response()->view('errors.404', [], 404); // 返回自定义的 404 错误页面
- }
- // 捕获 ValidationException 并返回统一的 JSON 错误响应
- if ($exception instanceof ValidationException) {
- $errors = $exception->errors();
- return response()->json([
- 'code' => 0,
- // 'msg' => '参数校验失败',
- 'msg' => '参数校验失败 ' . array_keys($errors)[0] . ' - ' . reset($errors)[0],
- ], 422);
- }
- // 你可以在这里捕获所有的异常,进行日志记录
- if ($exception instanceof \Throwable) {
- // 记录日志
- Log::error($exception);
- // 返回统一的错误响应
- return response()->json(['code' => 0, 'msg' => '请求异常'], 400);
- }
- // 如果是其他类型的异常,交给父类处理
- return parent::render($request, $exception);
- }
- }
|