close

Q: 如何在laravel中去catach DB query的exception

A: 

程式開頭要use Illuminate\Database\QueryException;

在catch中使用Illuminate\Database\QueryException,此時dd出來的message就是詳細的錯誤內容

※ 注意一旦出現exception,整個程式就是die,後面程式不會被執行。

--

The simplest way to catch any sql syntax or query errors is to catch an Illuminate\Database\QueryException after providing closure to your query:

 

try { 
  $results = \DB::connection("example")
    ->select(\DB::raw("SELECT * FROM unknown_table"))
    ->first(); 
    // Closures include ->first(), ->get(), ->pluck(), etc.
} catch(\Illuminate\Database\QueryException $ex){ 
  dd($ex->getMessage()); 
  // Note any method of class PDOException can be called on $ex.
}

 

If there are any errors, the program will die(var_dump(...)) whatever it needs to.

Note: For namespacing, you need to first \ if the class is not included as a use statement.

Also for reference: Laravel 5.1 API - Query Exception.

--

轉自 https://stackoverflow.com/questions/33679996/how-do-i-catch-a-query-exception-in-laravel-to-see-if-it-fails

--

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 dizzy03 的頭像
    dizzy03

    碎碎念

    dizzy03 發表在 痞客邦 留言(0) 人氣()