Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

Also for reference:

Laravel 5.5 API - Query Exception

Laravel 8.x API - Query Exception


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...