0

I have a web app that uses PHP to produce some JSON, which I capture in javascript and add to my DOM. If I raise a notice in PHP, it will try to print HTML. This breaks the javascript, which is trying to parse out JSON.

<br />
<b>Notice</b>:  Undefined property: MyClass::$serialize_option in <b>/Users/GoldenJoe/Development/Web Services/MyApp/api/v1/database_model/MyModel.php</b> on line <b>92</b><br />

It's fine to break a dev environment, but I'd really prefer it if these messages appeared in my error log instead. Is there a ways to control this in the configuration?

GoldenJoe
  • 7,874
  • 7
  • 53
  • 92
  • 2
    I recommend addressing the source of the error, but it's possible to [disable PHP's notices](https://stackoverflow.com/questions/2867057/how-do-i-turn-off-php-notices). – showdev Jan 28 '20 at 03:22
  • @GoldenJoe are you using any frameworks? – Boopathi D Jan 28 '20 at 03:26
  • 1
    [set_error_handler](https://www.php.net/manual/en/function.set-error-handler) can catch most errors - certainly all those which will not completely break your site anyway – Nick Jan 28 '20 at 03:28
  • Even if you set `display_errors = Off` like showdev references, your JSON may still break if it doesn't get back any response, which is what will happen in such a case when you suppress the error. If you want to go the extra mile, you could write your own error handler function via `set_error_handler`. What I've done with my own app is generate a UUID to display to the user, while writing the actual error message to an ElasticSearch log. User can contact us with that UUID and we can look at the logs to see what the error was. Admittedly, it is a lot of work setting this up. – David Tran Jan 28 '20 at 03:33
  • Well I don't want to turn errors off completely. I'd just like to keep my PHP errors isolated to the PHP environment, and not have them break my page because they wanted to tell me twice... – GoldenJoe Jan 28 '20 at 03:36
  • Setting `display_errors = Off` should still result in the error being output to your error log file. I tested just now, but you should confirm, just to be sure. – David Tran Jan 28 '20 at 03:40

1 Answers1

1

You can save that error message into variable by doing like this:

ob_start(); // put this before the expecting errors

$test = $t + 1; // notice that $t is undefined here, it will throw a NOTICE

$output = ob_get_clean(); // we will prevent that NOTICE to appear and store it into variable instead

echo 'this is my error '.$output.' -- end of error'; // you can now save this message into your log
Jonel Zape
  • 42
  • 6