簡體   English   中英

在 laravel 的 controller 內是否需要 try catch 塊?

[英]Is try catch block necessary inside controller in laravel?

我目前正在和我的朋友一起做一個項目。 他遵循這種編寫代碼的方法。 是好還是壞? 我也不是那么有經驗的開發人員。

public function store(Request $request)
 {  
    try   
    {  
        $comment = new TicketComment();  
        $comment->content = $request['comment'];  
        $comment->user_id = Auth::user()->id;  
        $comment->ticket_id = $request['ticketId'];  
        $comment->save();  
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();  
        $ticket->updated_at = $comment->created_at;  
        $ticket->update();  
    }    
    catch(Exception $e)  
    {  
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');  
        return redirect()->back();  
    }  
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');  
    return redirect()->back();  
}  

處理錯誤總是好的。 然而,Laravel 內置了錯誤處理,可以簡化這個過程。 這並不意味着您不需要 try catch 塊。 閱讀有關 laravel 錯誤處理的更多信息: https ://laravel.com/docs/5.8/errors

不要有廣泛的 Exception catch 塊。 僅捕獲您希望在該塊中拋出的異常,這樣您就可以正確記錄意外異常並修復代碼中可能導致這些異常的任何其他錯誤,而不是將它們隱藏起來。

如果您必須這樣做,那么它可能是在以下情況下:

public function store(Request $request)
 {  
    try   
    {  
        $comment = new TicketComment();  
        $comment->content = $request['comment'];  
        $comment->user_id = Auth::user()->id;  
        $comment->ticket_id = $request['ticketId'];  
        $comment->save();  
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();  
        $ticket->updated_at = $comment->created_at;  
        $ticket->update();  
    }    
    catch(Exception $e)  
    {  
        if (!($e instanceof SQLException)) {
            app()->make(\App\Exceptions\Handler::class)->report($e); // Report the exception if you don't know what actually caused it
        }
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');  
        return redirect()->back();  

    }  
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');  
    return redirect()->back();  
}  

這樣,任何意外的異常仍將被報告,您可以稍后查看日志以修復導致它們的任何錯誤。

提醒一下,自 PHP 7.1 起,您可以在 catch 塊(參考)中擁有異常聯合,例如

try { } 
catch (ExceptionType1|ExceptionType2 $e) {

}

通過這種方式,您可以處理您知道可以處理的異常,而讓 Laravel 處理您不確定如何處理的異常。

請注意,您通常不必在控制器代碼中使用try-catch塊,如果這是您首選的處理方式,您始終可以使用異常處理程序為所有未處理的異常執行 flash/redirect back 組合。

即使那個 Laravel 有他自己的內置錯誤處理,你最好使用try & catch 不要在開發模式下使用它,而是在生產模式下使用它。 try & catch的使用是用戶友好的,這意味着用戶不會看到由 laravel 產生的錯誤的傳統頁面(如果有任何錯誤),但會看到您的默認消息。

如何使用它的示例:

public function index()
{
   try {

           return view('index.blade.php');

   } catch (\Exception $exception) {

           \Log::error($exception);

           return redirect()->back()->with(['message' => 'There was an error']);
   }
}

如果你看到這部分\\Log::error($exception); ,這意味着 laravel 產生的錯誤將被記錄在storage/logs/laravel.log下的日志文件中,因此您作為開發人員可以看到該方法的問題。 另一方面,如果訪問頁面出現問題: view('index.blade.php')用戶將被重定向回上一頁,並在session保存一條消息,即: 'There was an error'

要在刀片出現錯誤時捕獲消息,您應該:

           @if (session('message'))
            <div class="container">
                <div class="alert alert-danger text-center">{{ session('message') }}</div>
            </div>
            @endif

快樂編碼!

這是我如何處理的。 我記錄了錯誤,而不是將其返回到用戶界面。

public function postData()
{
 try
  {
    //your logics to post goes here
  } 
      catch (\Exception $exception) {

                if (!($exception instanceof \SQLiteException)) {
                    app()->make(\App\Exceptions\Handler::class)->report($exception); // Report the exception if you don't know what actually caused it

                }
                Alert::toast('Error Toast', 'An error occurred');

                \Log::error($exception);

                return redirect()->back();

            }
            Alert::success('SuccessAlert', 'alert');
            return back();
        }

暫無
暫無

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

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