简体   繁体   中英

How to catch SQL Exception in Laravel 5

Hay I'm creating a code like this :

\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);

But it seems that my Exception never get hit. So how to capture exception in laravel when something wrong in sql query...??

Thanks in advance.

Try this

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

OR

use Illuminate\Database\QueryException;

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

My case: add \\ before Exception class otherwise it not handle

try
{
//write your codes here
}

catch(\Exception $e) {

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

Make sure to use the Exception library in your controller. From there you can do:

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

To implement an exception in Laravel, simply include the Exception class, at the top of your controller as

Use Exception;

Then wrap the lines of code you wish to catch an exception on using try-catch statements

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

You can also return your errors in json format, incase you are making an Ajax request, this time, remember to include the Response class at the top of your controller

Use Response;
Use Exception;

then wrap your codes in a try-catch statement as follows

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

I hope this will solve your problem, you can learn more on Laravel and Error handeling here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM