如何在 Laravel 5 中捕获 SQL 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40040636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:36:23  来源:igfitidea点击:

How to catch SQL Exception in Laravel 5

phpsqllaravellaravel-5

提问by Maryadi Poipo

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...??

但似乎我的异常永远不会被击中。那么当sql查询出错时如何在laravel中捕获异常......?

Thanks in advance.

提前致谢。

回答by Akshay Deshmukh

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

回答by Sunil shakya

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

我的情况:在 Exception 类之前添加 \ 否则它不会处理

try
{
//write your codes here
}

catch(\Exception $e) {

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

回答by fabian

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

回答by Ogbonna Vitalis

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 和错误处理的更多信息