简体   繁体   English

如何在Laravel 5中捕获SQL异常

[英]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. 但是似乎我的Exception从未被击中。 So how to capture exception in laravel when something wrong in sql query...?? 那么,当sql查询出现问题时,如何在laravel中捕获异常?

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 我的情况:在Exception类之前添加\\,否则无法处理

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 要在Laravel中实现异常,只需在控制器顶部添加Exception类即可,

Use Exception;

Then wrap the lines of code you wish to catch an exception on using try-catch statements 然后使用try-catch语句包装您希望捕获异常的代码行

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 您也可以以json格式返回错误,以防您正在发出Ajax请求,这一次,请记住在控制器顶部包括Response类。

Use Response;
Use Exception;

then wrap your codes in a try-catch statement as follows 然后将您的代码包装在try-catch语句中,如下所示

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 希望这能解决您的问题,您可以在此处了解有关Laravel和错误处理的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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