Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel try/catch doesn't work for a failed query

i have a INSERT query which might fail due to certain unique key in database so im using try/catch to avoid the error ...btw form_id is unique

    try {

        $reward = new UserCreditForm();
        $reward->user_id = $form->user_id ;
        $reward->form_id = $form->id ;
        $reward->amount = $amount ;
        $reward->result = $result ;
        $reward->save();
        $form->result = $result ;
        $form->save();

    }
    catch ( Exception $e )
    {
        $form->error_flag = 6 ;
        $form->save();
    }

but try/catch doesnt workwhen uniqu key fails and i get

Whoops, looks like something went wrong.
(2/2) QueryException

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'user_credit_forms_form_id_unique' (SQL: insert into `user_credit_forms` (`user_id`, `form_id`, `amount`, `result`, `updated_at`, `created_at`) values (2, 1, 499392, 1, 2017-08-31 14:45:06, 2017-08-31 14:45:06))

is there anyway to avoide the error and jump on the catche part if query fails ?

like image 652
hretic Avatar asked Jan 30 '23 16:01

hretic


2 Answers

You should use catch ( \Exception $e ) to catch all exceptions in try.

Final form should look like this:

try {

    $reward = new UserCreditForm();
    $reward->user_id = $form->user_id ;
    $reward->form_id = $form->id ;
    $reward->amount = $amount ;
    $reward->result = $result ;
    $reward->save();
    $form->result = $result ;
    $form->save();

}
catch ( \Exception $e )
{
    $form->error_flag = 6 ;
    $form->save();
}
like image 64
Yupik Avatar answered Feb 02 '23 08:02

Yupik


Way 1:

You need to use

\Illuminate\Database\QueryException $e

in your catch

} catch (\Illuminate\Database\QueryException $e) {

Reference for QueryException


Way 2:

You can alternatively use:

} catch (\Exception $e) {
like image 35
Thamilhan Avatar answered Feb 02 '23 10:02

Thamilhan