Does PHP get warnings and error messages?

I want to receive warnings and error messages in php $ variables, so I save them in my database.

For example, when there is any error, warning, or the like:

Parse error: syntax error, unexpected T_VARIABLE in /example.php(136) on line 9 Warning: [...] 

I want to get them in the $ error_code variable

How it's done?

+4
source share
4 answers

For a simple case of their registration:

 set_error_handler(function($errno, $errstr, $errfile, $errline) use ($db) { // log in database using $db->query() }); 

Instead of just writing them to your database (with the likelihood you won't look at them after a while), you can also let these warnings, notifications, etc. throw an exception:

 function exception_error_handler($errno, $errstr, $errfile, $errline) { if (error_reporting()) { // skip errors that were muffled throw new ErrorException($errstr, $errno, 0, $errfile, $errline); } } set_error_handler("exception_error_handler"); 

Source: ErrorException

An exception will have more serious side effects, so you should have

+5
source

Take a look at set_error_handler()

Sets the user function (error_handler) to handle errors in the script.

This function can be used to determine your own way of handling errors at runtime, for example, in applications where you need to clear data / files when a critical error occurs or when you need to trigger an error under certain conditions (using trigger_error ()).

+3
source

I am using error_get_last(); until I find a better solution

 $lastError = error_get_last(); echo $lastError ? "Error: ".$lastError["message"]." on line ".$lastError["line"] : ""; // Save to db 
+2
source

There is a variable called $ php_errormsg that receives the previous error message. Check here for more information - http://php.net/manual/en/reserved.variables.phperrormsg.php

0
source

All Articles