SQL 如何在 Laravel 中捕获查询异常以查看它是否失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33679996/
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-01 04:10:35  来源:igfitidea点击:

How do I catch a query exception in laravel to see if it fails?

sqllaravel-5

提问by KingKongFrog

All I'm trying to do is verify a query.

我要做的就是验证查询。

'SELECT * from table_that_does_not_exist'

Without that erroring out, I'd like to know it failed so I can return a response that states "Error: table does not exist" or the generic error.

如果没有那个错误,我想知道它失败了,所以我可以返回一个响应,指出“错误:表不存在”或一般错误。

回答by Tim Lewis

The simplest way to catch any sqlsyntax or query errors is to catch an Illuminate\Database\QueryExceptionafter providing closure to your query:

捕获任何sql语法或查询错误的最简单方法是Illuminate\Database\QueryException在为查询提供闭包之后捕获:

try { 
  $results = \DB::connection("example")
    ->select(\DB::raw("SELECT * FROM unknown_table"))
    ->first(); 
    // Closures include ->first(), ->get(), ->pluck(), etc.
} catch(\Illuminate\Database\QueryException $ex){ 
  dd($ex->getMessage()); 
  // Note any method of class PDOException can be called on $ex.
}

If there are any errors, the program will die(var_dump(...))whatever it needs to.

如果有任何错误,程序将die(var_dump(...))根据需要执行任何操作。

Note: For namespacing, you need to first \if the class is not included as a usestatement.

注意:对于命名空间,\如果该类未作为use语句包含,则需要首先。

Also for reference: Laravel 5.1 API - Query Exception

另供参考:Laravel 5.1 API - 查询异常

回答by Ogbonna Vitalis

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

Do not forget to include the Exception class at the top of your controller by saying

不要忘记通过说在控制器顶部包含 Exception 类

Use Exception;

回答by Ashraf Hefny

If you want to catch all types of database exceptions you can catch it on laravel Exception Handler

如果你想捕获所有类型的数据库异常,你可以在 Laravel 上捕获它Exception Handler

if ($exception instanceof \PDOException) {
    # render a custom error
}