【问题标题】:Is this a bug from the PHP Exception system?这是来自 PHP 异常系统的错误吗?
【发布时间】:2014-03-06 18:33:30
【问题描述】:

我有:

<?php

    try 
    {
        throw new Exception('Debes iniciar sesión para esto.', 1); // This is a null exception.
        throw new Exception('Debes iniciar sesion para esto.', 1); // This is not a null exception.
    }
    catch (Exception $ex1) 
    {
        echo 'Message: ' . $ex1->getMessage();
    }

当我抛出第一个异常时,结果为空!!处理时我无法收到消息!但由于某种原因,如果我删除重音,它会正确抛出消息。

可能是什么?一个错误? (不信你自己试试)

【问题讨论】:

标签: php exception behavior


【解决方案1】:

有效:http://codepad.viper-7.com/MDs4NB。您缺少用于打印字符串和错误消息的 echo 语句:

try 
{
    throw new Exception('Debes iniciar sesión para esto.', 1); // This is a null exception.
    throw new Exception('Debes iniciar sesion para esto.', 1); // This is not a null exception.
}
catch (Exception $ex1) 
{
    echo 'Message: ' . $ex1->getMessage();
}

【讨论】:

  • 抱歉错字(这是一个快速的片段)但很奇怪,我在我的环境中看不到消息(5.3.5)
  • 为什么要投票?缺少的echo 可能是原始问题中的错字(更新:it was
  • 但正如小提琴所示,这段代码有效。所以这不是代码的错误。
【解决方案2】:

我的错,它与 PHP 无关,正如 John Conde 所说,问题是我忘记了使用 json_encode 例外,而 json_encode 不喜欢非 utf8 字符,所以我有类似的东西:

try 

{

 throw new Exception('Debes iniciar sesión para esto.', 1);

}

catch (Exception $ex1) 

{

 echo json_encode(array('message' => $ex1->getMessage()));

}

因此,当 json_encode 检测到非 utf8 数据时,它将返回 NULL,因此为了解决此问题,我们必须在获取 json 之前将数据显式编码为 utf8:

json_encode(array('message' => utf8_encode('Canción.')));

结果将生成一个带有十六进制字符格式的 JSON(即 \x00),以及它们各自的 ASCII 代码。很抱歉,当它对我不利时,它告诉这是 PHP 问题。但是,我会接受 John 的回答,因为他回答正确并且值得称赞,但我也会留下我的答案,以提供问题的真正原因。

【讨论】:

  • 感谢您发布根本原因。
猜你喜欢
  • 2023-03-20
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2016-02-22
相关资源
最近更新 更多