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

前端 未结 3 671
甜味超标
甜味超标 2020-12-15 16:28

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

相关标签:
3条回答
  • 2020-12-15 17:08

    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.

    Also for reference: Laravel 5.1 API - Query Exception

    0 讨论(0)
  • 2020-12-15 17:17

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

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

    for more details about how to use laravel Exception Handler check https://laravel.com/docs/7.x/errors

    0 讨论(0)
  • 2020-12-15 17:26

    Wrap the lines of code you wish to catch an exception on using try-catch statements

    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

    Use Exception;
    
    0 讨论(0)
提交回复
热议问题