0

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?

Jorge Guberte
  • 10,464
  • 8
  • 37
  • 56

2 Answers2

2

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.

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
1

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

vicentazo
  • 1,739
  • 15
  • 19