问题
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