duanping2809 2016-11-30 14:56
浏览 29
已采纳

捕获查询异常?

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.

  • 写回答

2条回答 默认 最新

  • dongsi073898 2016-11-30 15:17
    关注

    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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料