Laravel捕捉雄辩的“独特”字段错误

2022-08-30 13:34:57

我试图在Laravel中使用雄辩地插入记录时进行识别,当它由于唯一字段错误而引发异常时。

到目前为止,我的代码是:

try {

    $result = Emailreminder::create(array(
                       'user_id' => Auth::user()->id,
                       'email' => $newEmail,
                       'token' => $token,
              ));

} catch (Illuminate\Database\QueryException $e) {
    return $e;
}

它抛出一个异常,好吧,我只是不知道如何将其标识为列重复错误?

谢谢

加文。


答案 1

我假设你使用MySQL,对于其他系统来说可能有所不同

好的,首先,重复条目的错误代码是1062。以下是从异常中检索错误代码的方法:

catch (Illuminate\Database\QueryException $e){
    $errorCode = $e->errorInfo[1];
    if($errorCode == 1062){
        // houston, we have a duplicate entry problem
    }
}

答案 2

在类处理程序中添加此代码(异常)

if($e instanceof QueryException){
        $errorCode = $e->errorInfo[1];          
        switch ($errorCode) {
            case 1062://code dublicate entry 
                return response([
                    'errors'=>'Duplicate Entry'
                ],Response::HTTP_NOT_FOUND);    
                break;
            case 1364:// you can handel any auther error
                return response([
                    'errors'=>$e->getMessage()
                ],Response::HTTP_NOT_FOUND);                        
                break;      
        }
     }
    ...
    return parent::render($request, $exception);

推荐