簡體   English   中英

在 Laravel(會話或變量)中存儲錯誤消息的最佳方式

[英]best way to store error messages in Laravel (session or variable)

我正在嘗試找出存儲錯誤消息的最佳方式(例如,由於錯誤的參數)。

假設我在 Controller 中聲明接受的參數,但如果給出了任何其他參數,我想顯示一個頁面,該頁面只顯示錯誤消息“給出了錯誤的參數”。
非常簡單的代碼示例:

if ($param == 'example') {
  // some code
} else {
  // accepting no other parameter and should return a page with an error message
  // session? variable?
}
return view('index/example');
  1. 我可以使用以下會話:

    • 正常 session: session()->put(...)
      問題:如果我不手動刪除數據,數據就會保留

    • flash 給 session 的消息: session()->flash(...)
      問題:這是為了下一個請求,所以當我更正錯誤的參數時,我必須重新加載兩次才能加載正確的頁面

    • 當前請求為 session: session()->now(...);
      問題: ??

  2. 我也可以使用普通變量:

    • $error = 'message;
      return view('index', compact('error'));
      問題:如果不手動刪除帶有錯誤消息的變量將被保留

我知道 session flash 消息是為此類消息創建的,但由於我在上面簡要說明的問題,我真的不想使用它。

我想知道每種方法的(缺點)優點,以及哪種方法最好,或者是否有推薦的方法實際上效果很好。

我推薦我用於項目的這段代碼:

/*
 * Add an error to Laravel session $errors
 * @author Pavel Lint
 * @param string $key
 * @param string $error_msg
 */
function add_error($error_msg, $key = 'default') {
    $errors = Session::get('errors', new ViewErrorBag);

    if (! $errors instanceof ViewErrorBag) {
        $errors = new ViewErrorBag;
    }

    $bag = $errors->getBags()['default'] ?? new MessageBag;
    $bag->add($key, $error_msg);

    Session::flash(
        'errors', $errors->put('default', $bag)
    );
}

這使您可以將錯誤存儲在 Laravel 本身所在的位置。 您將受益於$errors變量在您的所有刀片模板中自動可用。 然后在刀片的某個地方,這段標准代碼會顯示錯誤:

@if ($errors->any())
    <div class="alert alert-danger">
        There were some errors with your request.
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

在我的情況下,即使正在向用戶發送正確的錯誤響應,我也試圖存儲我的驗證錯誤。 即使在生產中,我也設法通過檢查app/Exceptions/Handler.php class 中的異常 class 來解決這個問題

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Throwable  $exception
 * @return \Symfony\Component\HttpFoundation\Response
 *
 * @throws \Throwable
 */
public function render($request, Throwable $exception)
{
    if ($exception instanceof ValidationException) {
        Log::debug($exception->errors(), $exception->getTrace());
    }

    return parent::render($request, $exception);
}

注意:我使用望遠鏡觀察日志作為設置:

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    // Telescope::night();

    $this->hideSensitiveRequestDetails();

    Telescope::filter(function (IncomingEntry $entry) {
        if ($this->app->environment('local')) {
            return true;
        }

        return $entry->isReportableException() ||
            $entry->isFailedRequest() ||
            $entry->isFailedJob() ||
            $entry->isScheduledTask() ||
            $entry->type === EntryType::LOG ||
            $entry->type === EntryType::JOB ||
            $entry->type === EntryType::MAIL ||
            $entry->type === EntryType::QUERY ||
            $entry->hasMonitoredTag();
        });
    }
request()->session()->flash('default', 
    request()->session()->get('default', new ViewErrorBag)->put('errors', 
        new MessageBag(['Error message.'])
    )
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM