如何在laravel中捕获查询异常以查看其是否失败? [英] How do I catch a query exception in laravel to see if it fails?
问题描述
我要做的就是验证查询.
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.
推荐答案
捕获任何sql
语法或查询错误的最简单方法是在为查询提供闭包后捕获Illuminate\Database\QueryException
:
The simplest way to catch any sql
syntax or query errors is to catch an Illuminate\Database\QueryException
after providing closure to your query:
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.
}
如果有任何错误,程序将根据需要die(var_dump(...))
.
If there are any errors, the program will die(var_dump(...))
whatever it needs to.
注意:对于命名空间,如果该类未包含在use
语句中,则需要先\
.
Note: For namespacing, you need to first \
if the class is not included as a use
statement.
也可供参考: Laravel 5.1 API-查询异常
这篇关于如何在laravel中捕获查询异常以查看其是否失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!