【问题标题】:Symfony - Exception get message string comparisonSymfony - 异常获取消息字符串比较
【发布时间】:2015-03-05 11:27:03
【问题描述】:

我有问题。我正在捕获异常,我想根据异常消息个性化错误消息。

所以我想检查我的 excpetion 是否包含某个字符串以显示特定消息。 这是我的代码:

  try {
                    $em->persist($document);
                    $em->flush();
                } catch (\Exception $ex) {

                    $error = "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry";

                    throw new \Exception('Erreur lors de l\'upload du fichier');
                }

所以我想做类似的事情

if($ex->getMessage() "contain" $error){throw new \Exception....}

但不知道怎么做

有人有想法吗? 谢谢

【问题讨论】:

  • 你可以试试php中的strpos方法

标签: php symfony exception comparison


【解决方案1】:

我建议您为此类情况指定例外情况。因此,您将捕获一个像这样的特殊异常,而不是解析消息字符串:

try {
    ...
}
catch(NotFoundException) {
}
catch(CustomException) {}

等等

在 Symfony 中,您还可以定义内核异常侦听器(在此处查看更多详细信息:http://symfony.com/doc/current/cookbook/service_container/event_listener.html)并根据其类型处理您的异常。

【讨论】:

  • 谢谢我解决了我的问题,但我会看看这个也许它会更干净
【解决方案2】:

正如对我的问题的评论中回答的那样,我使用 strpos 方法解决了我的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2010-10-01
    • 2013-04-19
    • 2014-03-14
    • 1970-01-01
    • 2014-06-14
    相关资源
    最近更新 更多