Cannot catch PDOException in laravel 3
Asked Answered
A

1

6

I'm trying to catch a PDOException in laravel 3 but it seems as if I cannot do this. My code is as follows:

try{
    DB::connection()->pdo->beginTransaction();

    Myobject::create($cleaned_input_array);

    // do other stuff that could possibly throw a custom exception

    DB::connection()->pdo->commit();
}
catch(\PDOException $e)
{
    DB::connection()->pdo->rollBack();
    return HTTP_STATUS::response(BAD_REQUEST, array("error creating");
}
catch(Exception $e)
{
    DB::connection()->pdo->rollBack();
    return HTTP_STATUS::response(BAD_REQUEST, array($e->getMessage()));
}

The general exception is caught if the other parts in the 'try' throw an exception. If they do not, everything runs clean. If the create has an issue executing the MYSQL statement it does not throw a PDOException, it is only throwing a general Exception.

Ardeth answered 7/5, 2014 at 19:42 Comment(6)
why is there a \ in front of your PDOExceptionUltramicroscope
I've read you can place a '\' in front of PDOException for namespace issues. Even if I remove the '\' I still am unable to catch a PDOException. I should note that the error on the create is being thrown as a general exception...Ardeth
Why not dump out the type of $e, eg get_class($e)? That will at least tell you the type of exception being caught in the general exception handlerAdjudicate
Please expand Myobject which seems to be relevant (you expect it to throw a PDOException!) so that people can easily reproduce the issue.Suber
Please remove the first catch block and var_dump the generic Exception that you are supposed to get when PDOException is thrown...Miscellaneous
Without knowing what the DB class is throwing, there's no way to answer this.Rustication
F
-1

A model wouldn't actually throw PDOException, that would be caught internally and a \Illuminate\Database\QueryException would be thrown instead, try catching that.

Famagusta answered 7/5, 2014 at 21:6 Comment(6)
That is not being caught either. To be clear, I simply replaced \PDOException with QueryException in the above code and the regular Exception is all that is being caught.Ardeth
If your code is namespaced you'll need to provide the fully qualified namespace, otherwise it'll never be caught.Famagusta
My code is not name spaced, I was merely copying the example which showed the example. I only have one instance of that class/method. Thus, the question still remains...Ardeth
Wouldn't it be catch (\Illuminate\Database\QueryException $queryException) in the global namespace (which OP is apparently in)? That being said, QueryException extends PDOException anywayAdjudicate
Yeah, either way, I'm pretty sure it needs to be the full namespace, exceptions are a bit funny tbh. @Ardeth just for arguments sake, try removing the Exception catch.Famagusta
Illuminate has nothing to do with Laravel 3!Suber

© 2022 - 2024 — McMap. All rights reserved.