Exception message not being shown if json_encode is applied to the output

旧街凉风 提交于 2019-12-12 02:53:38

问题


Here's the code:

try{
//The exception is thrown.
throw new Exception('Parâmetros de consulta inválidos');

// and in the catch block it's caught successfully:
}catch(Exception $e){
    echo $e->getMessage(); //This prints the message correctly.

    $output = json_encode(array('msg'=>$e->getMessage()));
    echo $output; //But this fails...displays {"msg":null}

}

What is the issue here?


回答1:


The problem is with the character â and á. Infact, if you replace them with a simple a, you'll get the right message.

Replace this line:

array('msg'=>$e->getMessage())

with this:

array('msg'=>utf8_encode($e->getMessage()))

You have to do this change because the json_encode works with ut8 as you can read here.




回答2:


If you use a PHP version >= 5.4.0, you should call to the json_encode function with the JSON_UNESCAPED_UNICODE flag. http://php.net/manual/en/function.json-encode.php



来源:https://stackoverflow.com/questions/7836813/exception-message-not-being-shown-if-json-encode-is-applied-to-the-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!