Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: try/catch fail

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

like image 596
mOrloff Avatar asked Jan 06 '14 18:01

mOrloff


1 Answers

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)
like image 60
Machavity Avatar answered Nov 07 '22 00:11

Machavity