捕获查询异常?

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.

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

You can check errorInfo of the exception object

It looks like this..

+errorInfo: array:3 [▼
0 => "23000"
1 => 1062
2 => "Duplicate entry 'abc@gmail.com' for key 'users_email_unique'"

You can write following code in catch..

 try{}
    catch(QueryException $qe){
    If ($qe->errorInfo[0] == "23000" && $qe->errorInfo[1] == "1062"){
        return "Your message"
    }else{
        return "General Message"
    } 
}