panthro panthro - 10 days ago 8
PHP Question

Catching a query exception?

I have a slug column in my database, it's unique.

If I try and store another row with a non unique slug I get a QueryException error.

I catch the error, and hope to return an error message something along the lines that "slug exists".

try {
User::create($data);
} catch (\Illuminate\Database\QueryException $e) {
//return the error
}


The above is fine, but I'm just wondering, what if another QueryException is thrown, not to do with the duplicate slug and i return a duplicate slug error message incorrectly.

Is there a way to find out what the query exception was and return an error message based on this? i know the exception provides its own message but I was hoping for something a little more user friendly.

Mjh Mjh
Answer

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
    }
}