Laravel是怎么处理ValidationException的和怎么通知到界面上显示的

问题描述?

在看官方的Laravel Breeze项目,为什么认证的时候抛出一个异常,界面上可以接收到这个异常信息并显示呢

下面是当点击登录去认证的代码

public function authenticate()
    {
        $this->ensureIsNotRateLimited();

        if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
            RateLimiter::hit($this->throttleKey());

            throw ValidationException::withMessages([
                'email' => trans('auth.failed'),
            ]);
        }

        RateLimiter::clear($this->throttleKey());
    }

对应的视图, 当认证的时候抛出一个异常的时候,为什么下面的x-auth-validation-errors就会收到相应的错误信息?

<x-guest-layout>
    <x-auth-card>
        <x-slot name="logo">
            <a href="/">
                <x-application-logo class="w-20 h-20 fill-current text-gray-500" />
            </a>
        </x-slot>

        <!-- Session Status -->
        <x-auth-session-status class="mb-4" :status="session('status')" />

        <!-- Validation Errors -->
        <x-auth-validation-errors class="mb-4" :errors="$errors" />
        ...
君子博学而日参省乎己,则知明而行无过矣
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

找到处理的相关代码了:

  1. ShareErrorsFromSession类中的handle方法负责从session中获取错误信息,并放在errors变量中

  2. 捕获ValidationException 异常是在Handler类中

    public function render($request, Throwable $e)
    { 
    ...
     if ($e instanceof HttpResponseException) {
             return $e->getResponse();
         } elseif ($e instanceof AuthenticationException) {
             return $this->unauthenticated($request, $e);
         } elseif ($e instanceof ValidationException) {//就是在这里处理的
             return $this->convertValidationExceptionToResponse($e, $request);
         }
      ...
    }
  3. 把相关错误信息放在session中 RedirectResponse类

    public function withErrors($provider, $key = 'default')
     {
         $value = $this->parseErrors($provider);
    
         $errors = $this->session->get('errors', new ViewErrorBag);
    
         if (! $errors instanceof ViewErrorBag) {
             $errors = new ViewErrorBag;
         }
    
         $this->session->flash(
             'errors', $errors->put($key, $value)
         );
    
         return $this;
     }
1年前 评论
讨论数量: 6

try捕捉对应的异常信息,然后赋值页面,就可以展示出来了,开发过程中也会有不同的异常,参数错误,权限不足等等

1年前 评论
zstartw (楼主) 1年前

找到处理的相关代码了:

  1. ShareErrorsFromSession类中的handle方法负责从session中获取错误信息,并放在errors变量中

  2. 捕获ValidationException 异常是在Handler类中

    public function render($request, Throwable $e)
    { 
    ...
     if ($e instanceof HttpResponseException) {
             return $e->getResponse();
         } elseif ($e instanceof AuthenticationException) {
             return $this->unauthenticated($request, $e);
         } elseif ($e instanceof ValidationException) {//就是在这里处理的
             return $this->convertValidationExceptionToResponse($e, $request);
         }
      ...
    }
  3. 把相关错误信息放在session中 RedirectResponse类

    public function withErrors($provider, $key = 'default')
     {
         $value = $this->parseErrors($provider);
    
         $errors = $this->session->get('errors', new ViewErrorBag);
    
         if (! $errors instanceof ViewErrorBag) {
             $errors = new ViewErrorBag;
         }
    
         $this->session->flash(
             'errors', $errors->put($key, $value)
         );
    
         return $this;
     }
1年前 评论

框架運行的時候 會實例化 Kernel類

file

就這個這個類

file

運行這個類中的handle方法 handle方法中調用了 sendRequestThroughRouter 這個方法

file

sendRequestThroughRouter方法中調用了 bootstrap方法

file

bootstrap 方法中會加載註冊

file

其中有一個 HandleExceptions 這個類 就是處理錯誤的

file

裡面註冊了兩個函數 set_error_handler 和 set_exception_handler

file

如果是像php錯誤 比如變量未定義這種就會被set_error_handler 這個函數捕捉到 就會觸發handleError 方法 file

然後handleError裡面throw 了一個 ErrorException 就會被 set_exception_handler 捕捉到 就會觸發handleException 方法 如果是在框架裡面直接 throw一個異常 就會直接被set_exception_handler 捕捉到

file

然後方法裡面調用了 getExceptionHandler 類 就是異常類 都會丟給這個錯誤處理類去處理錯誤 調用了 report 方法 這個方法是記錄異常到日誌系統的

file

然後還調用了 renderHttpResponse 這個方法

file

這個是做響應的 就是你說的《《ValidationException的和怎么通知到界面上显示》》 都是在這個方法裡面做的處理 你可以去看一個文檔 裡面有介紹這個

1年前 评论
zstartw (楼主) 1年前

这个厉害了,可以省很多个try

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!