From where and how do the error_level and error_message come in custom error handler function?

173 views Asked by At

I'm learning PHP from w3school's PHP Tutorial.

In a chapter "PHP Error Handling", I am studying about Creating Custom Error Handler.

I came across following program in which a Custom Error Handler Function is defined. See the below code.

<?php
  //error handler function
  function customError($errno, $errstr) {
    echo "<b>Error:</b> [$errno] $errstr";
  }

  //set error handler
  set_error_handler("customError");

  //trigger error
  echo($test);
?>

The output of above code is as below :

Error: [8] Undefined variable: test

My doubt is as I have not specified the error level and error message anywhere in the program then from where and how the custom error function is getting error level and error message?

How this whole custom error handling mechanism works in PHP?

Please explain me in simple and lucid language. You can explain with the help of some other example too. In fact it would be better for me to understand as well.

2

There are 2 answers

0
Mathias Barresi On BEST ANSWER

The error level your custom handler receives is one of PHP's E_* constants. You find the list of possible constants and their values here.

In your example the use of the undefined variable $test would normally cause a PHP Notice. Therefore you get the value 8 (which is E_NOTICE) as $errno in your custom handler. You cannot change the error message, as this error is generated internally by PHP.

Try it: remove the custom error handler and look at the error PHP gives you for using the undefinded variable. This is exactly the level and message your custom handler gets called with.

I suggest you try out your handler using the trigger_error() function (see here). This is the only way to set error level and message yourself.

Note also that it doesn't matter what is set in error_reporting ini setting! Your custom handler always receives ALL error messages regardless of the level.

Please read through the manual pages linked above.

0
Timurib On

Native errors

All errors that produced by PHP itself or by its extensions have the certain message and type (level of severity such as E_NOTICE, E_WARNING, E_ERROR, etc). This parameters are set in the source code. For your example, zend_execute.c:

static zend_never_inline ZEND_COLD void zval_undefined_cv(uint32_t var, const zend_execute_data *execute_data)
{
    zend_string *cv = CV_DEF_OF(EX_VAR_TO_NUM(var));

    zend_error(E_NOTICE, "Undefined variable: %s", ZSTR_VAL(cv));
}

Custom errors

You can generate an user-level error through the trigger_error() function. It allows to specify a custom message and one of E_USER_* types for the emitted error.

trigger_error("Some message", E_USER_ERROR);