How to Catch a Query Exception in Laravel to See If It Fails

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

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

How to handle Query Exception in Laravel?

Catch an exception on using try-catch statements :

Use Exception;

try
{
// write your codes here
}
catch(\Exception $e)
{
//dd($e->getMessage());
return "Something Went Wrong";
}

If you want to catch PDO Exception :

use PDOException;

try
{
//write your codes here
}
catch(\PDOException $e)
{
//dd($e->getMessage());
return "Something Went Wrong":
}

Catching a query exception?

To check if you got a QueryException because of a duplicate, check if $e->getCode() equals to 23000.

When a duplicate occurs due to a constraint, MySQL will issue signal SQLSTATE 23000 which you can use to determine what exactly went wrong. You can implement your own signal in MySQL to signal about various errors (via triggers etc)

Example:

try {
User::create($data);
} catch (\Illuminate\Database\QueryException $e) {
if($e->getCode() === '23000') {
// you got the duplicate
}
}

laravel try/catch doesn't work for a failed query

You should use catch ( \Exception $e ) to catch all exceptions in try.

Final form should look like this:

try {

$reward = new UserCreditForm();
$reward->user_id = $form->user_id ;
$reward->form_id = $form->id ;
$reward->amount = $amount ;
$reward->result = $result ;
$reward->save();
$form->result = $result ;
$form->save();

}
catch ( \Exception $e )
{
$form->error_flag = 6 ;
$form->save();
}

Laravel returning query exception with no error message

I removed the title part inheriting from post title while saving the imagepath. The new image now only inherits current date and time as filename and path.

$imagePath = $request->file('image')->storeAs('images/post', Carbon::now()  . '.' . $request->file('image')->getClientOriginalExtension(), 'public');

This project uses devanagari characters and seems like it had trouble saving the image path containing special characters from devanagari.

Laravel check for constraint violation

You are looking for the 23000 Error code (Integrity Constraint Violation). If you take a look at QueryException class, it extends from PDOException, so you can access to $errorInfo variable.

To catch this error, you may try:

try {
// ...

} catch (\Illuminate\Database\QueryException $e) {
var_dump($e->errorInfo);
}

// Example output from MySQL
array (size=3)
0 => string '23000' (length=5)
1 => int 1452
2 => string 'Cannot add or update a child row: a foreign key constraint fails (...)'

To be more specific (Duplicate entry, not null, add/update child row, delete parent row...), it depends on each DBMS:

  • PostgreSQL and SQL server follow the SQL standard's conventions for SQLSTATE code, so you may return the first value from the array $e->errorInfo[0] or call $e->getCode() directly
  • MySQL, MariaDB and SQLite do not strictly obey the rules, so you need to return the second value from the array $e->errorInfo[1]

For laravel, handling errors is easy, just add this code in your "app/start/global.php" file ( or create a service provider):

App::error(function(\Illuminate\Database\QueryException $exception)
{
$error = $exception->errorInfo;
// add your business logic
});


Related Topics



Leave a reply



Submit