簡體   English   中英

如何在Laravel 5中捕獲SQL異常

[英]How to catch SQL Exception in Laravel 5

干草我正在創建這樣的代碼:

\Log::info("saving log....");
    try{
        $data = AstronautCandidateLog::insert($request->logs);
    }catch (SQLException $e)
    {
        \Log::info("SQL Exception happened");
    }catch (Exception $e)
    {
        \Log::info("Exception happened");
    }

    \Log::info("status save data : ". $data);

但是似乎我的Exception從未被擊中。 那么,當sql查詢出現問題時,如何在laravel中捕獲異常?

提前致謝。

嘗試這個

try { 
 //Your code
} catch(\Illuminate\Database\QueryException $ex){ 
  dd($ex->getMessage()); 
}

要么

use Illuminate\Database\QueryException;

 try { 
     //Your code
    } catch(QueryException $ex){ 
      dd($ex->getMessage()); 
    }

我的情況:在Exception類之前添加\\,否則無法處理

try
{
//write your codes here
}

catch(\Exception $e) {

            Log::error($e->getMessage());
        }

確保在控制器中使用異常庫。 從那里您可以:

try{
    Some queries . . .
}catch(Exception $e){
    return response()->json([
      'error' => 'Cannot excecute query',
    ],422);
}

要在Laravel中實現異常,只需在控制器頂部添加Exception類即可,

Use Exception;

然后使用try-catch語句包裝您希望捕獲異常的代碼行

try
{
//write your codes here
}
catch(Exception $e)
{
   dd($e->getMessage());
}

您也可以以json格式返回錯誤,以防您正在發出Ajax請求,這一次,請記住在控制器頂部包括Response類。

Use Response;
Use Exception;

然后將您的代碼包裝在try-catch語句中,如下所示

try
{
//write your codes here
}
catch(Exception $e)
{
    return response()->json(array('message' =>$e->getMessage()));
}

希望這能解決您的問題,您可以在此處了解有關Laravel和錯誤處理的更多信息

暫無
暫無

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

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