PHP: try/catch fail
Asked Answered
D

1

8

I'm running WAMSERVER 2.4 (32-bit) with PHP 5.4.16, this is a Laravel 3 project.

In a try block, which I'm expecting to fail, I am submitting a duplicate row for insertion against a uniqueness constraint.
Instead of handling the exception in the catch, it's throwing an "Unhandled Exception" error from the try block and failing.

    // This throws an error if the relationship already exists.
    // If that happens, just pass it to the logger and move on.
    try {
        $entity->$pivotMethod()->attach( $rowData->get_key(), $ext );
    } catch (Exception $e) {
        $err = $e->getMessage()."\n";
        error_log($err);
    }

Here's the error it throws: Unhandled Exception

Message:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '695d7f0b-53b8-11e3-93fc-c12677e410a5-0-0-14-' for key 'unique'

SQL: INSERT INTO person_contact (person_uuid,phone_id) VALUES (?, ?)
Bindings: array( 0 => '695d7f0b-53b8-11e3-93fc-c12677e410a5', 1 => 14)

Location: C:\path\to\laravel\3_2_13\database\connection.php on line 263

Duarte answered 6/1, 2014 at 18:43 Comment(5)
If not exception is thrown it will never reach the catch blockGeneration
+1 Yes it is! You must throw exceptionsTeheran
Is your block above inside a class within a namespace?Tovatovar
try \Exception instead of ExceptionSunsunbaked
That did it (namespacing)! Thanks @Tovatovar and #DanFromGermany .. you guys are so smart :)Duarte
T
8

Based on your comment here's your problem

namespace Something;

class myClass {

    function method() {
          try {
        $entity->$pivotMethod()->attach( $rowData->get_key(), $ext );
       } catch (Exception $e) {
        $err = $e->getMessage()."\n";
        error_log($err);
       }
    }
}

In this case you're typehinting that you're catching an exception but you don't specify a scope so PHP is assuming you're catching \Something\Exception

The fix is pretty simple. Adding a \ tells PHP to catch anything that is, or extends, the base Exception class

catch (\Exception $e)
Tovatovar answered 6/1, 2014 at 18:50 Comment(3)
+1 I hope you didn't just get this answer from the comments, DanFromGermany found it out first :)Trattoria
I knew this solution because I had the same problem few months ago, but his guess came in first Is your block above inside a class within a namespace? Your all welcomeSunsunbaked
No, that's why I asked if it was in a namespace. I've run across this type of problem before. When you typehint like that, PHP gets VERY specific. Unless you know you're going to be catching a specific type of exception, it's almost always best to use \ExceptionTovatovar

© 2022 - 2024 — McMap. All rights reserved.