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.

2
  • Try catching \Illuminate\Database\QueryException Commented Oct 14, 2016 at 10:22
  • Still no luck @canVural.... Commented Oct 14, 2016 at 10:29

4 Answers 4

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()); 
    }
Sign up to request clarification or add additional context in comments.

1 Comment

At last i will suggest you to refer this link [stackoverflow.com/questions/31508223/… and [stackoverflow.com/questions/33679996/…. Hope this will help.
6

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

try
{
//write your codes here
}

catch(\Exception $e) {

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.