簡體   English   中英

如何在我的 laravel 9 項目中捕獲 MySQL/MariaDB 異常?

[英]How can I catch MySQL/MariaDB Exception in my laravel 9 project?

在我的訂閱表單中,我將 email 字段作為 PK。 我想處理異常錯誤“SQLSTATE [23000]:完整性約束違規:1062 重復條目”。

我該怎么做? PS:我插入到我的 Controller 內部的數據庫中

詢問:

if (isset($_POST['nom'], $_POST['prenom'], $_POST['email'], $_POST['cities'])) {
    $nom = request('nom');
    $prenom = request('prenom');
    $email = request('email');
    $ville = request('cities');
    DB::insert('insert into newsletter (nom, prenom, email, ville) values (?, ?, ?, ?)', [$nom, $prenom, $email, $ville]);
}
// put these at the top of the file with other imports
use Exception; 
use Illuminate\Support\Facades\Log;

try {
    DB::table('newsletter')->insert([
        'nom' => request('nom'),
        'prenom' => request('prenom'),
        'email' => request('email'),
        'ville' => request('ville'),
    ]);
} catch (Exception $exception) {
    // do whatever you want when exception happens
    Log::info($exception->getMessage());
}

暫無
暫無

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

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