10

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.

Maryadi Poipo
  • 1,418
  • 8
  • 31
  • 54

4 Answers4

18

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()); 
    }
Akshay Deshmukh
  • 1,242
  • 1
  • 16
  • 31
  • At last i will suggest you to refer this link [http://stackoverflow.com/questions/31508223/how-to-properly-catch-php-exceptions-laravel-5-1] and [http://stackoverflow.com/questions/33679996/how-do-i-catch-a-query-exception-in-laravel-to-see-if-it-fails]. Hope this will help. – Akshay Deshmukh Oct 14 '16 at 11:10
6

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

try
{
//write your codes here
}

catch(\Exception $e) {

            Log::error($e->getMessage());
        }
Sunil Shakya
  • 8,097
  • 2
  • 17
  • 20
1

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);
}
fabian
  • 21
  • 3
0

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

Ogbonna Vitalis
  • 7,969
  • 2
  • 11
  • 21