laravel 异常捕获,如何在laravel中捕获查询异常以查看其是否失败?

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.

解决方案

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.

}

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值