如何在 Laravel 中捕获查询异常以查看它是否失败? [英] How do I catch a query exception in laravel to see if it fails?

查看:13
本文介绍了如何在 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.

推荐答案

捕获任何 sql 语法或查询错误的最简单方法是捕获 IlluminateDatabaseQueryException 关闭您的查询后:

The simplest way to catch any sql syntax or query errors is to catch an IlluminateDatabaseQueryException 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(IlluminateDatabaseQueryException $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.5 API - 查询异常

Laravel 8.x API - 查询异常

这篇关于如何在 Laravel 中捕获查询异常以查看它是否失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆