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.
In Laravel 5 you can catch exceptions by editing the render method in app/Exceptions/Handler. php . This will be applied to ANY exception in AJAX requests. If your app is sending out an exception of App\Exceptions\MyOwnException , you check for that instance instead.
Try: Program statements that can raise the exception should be kept within a try block. Catch: If any exception occurs in the try block, it will be thrown. We can catch that exception using the Catch block and handle it in the code. Throw: System-generated exceptions are automatically thrown by JVM.
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.5 API - Query Exception
Laravel 8.x API - Query Exception
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With