Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP – Error Handling

In PHP, errors are handled somewhat differently compared to other languages. PHP will attempt to continue execution despite encountering errors until a fatal error occurs. Of course, it will provide notifications of these errors.

Each error generated by PHP includes a type. There is a list of these types, along with a brief description of their behavior and possible causes. Below is the list:

ValueConstantDescription
1 E_ERROR (integer) Runtime Fatal Errors. These indicate unrecoverable errors, such as a memory allocation problem. Script execution is halted.
2 E_WARNING (integer) Runtime warnings (non-fatal errors). Script execution is not halted.
4 E_PARSE (integer) Compile-time parse errors. Parse errors should only be generated by the parser.
8 E_NOTICE (integer) Runtime notices. Indicate that the script encountered something that could indicate an error, but could also occur during normal script execution.
16 E_CORE_ERROR (integer) Fatal errors occurring during PHP initialization. Similar to E_ERROR, except generated by the PHP core.
32 E_CORE_WARNING (integer) Warnings (non-fatal errors) occurring during PHP initialization. Similar to E_WARNING, except generated by the PHP core.
64 E_COMPILE_ERROR (integer) Fatal compile-time errors. Similar to E_ERROR, except generated by the Zend Script Engine.
128 E_COMPILE_WARNING (integer) Compile-time warnings (non-fatal errors). Similar to E_WARNING, except generated by the Zend Script Engine.
256 E_USER_ERROR (integer) User-generated error message. Similar to E_ERROR, except generated by PHP code using the trigger_error() function.
512 E_USER_WARNING (integer) User-generated warning message. Similar to E_WARNING, except generated by PHP code using the trigger_error() function.
1024 E_USER_NOTICE (integer) User-generated notice message. Similar to E_NOTICE, except generated by PHP code using the trigger_error() function.
2048 E_STRICT (integer) Enable to have PHP suggest changes to your code, ensuring best interoperability and compatibility with future PHP versions.
4096 E_RECOVERABLE_ERROR (integer) Catchable fatal error. Indicates a potentially dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user-defined handler (see also set_error_handler()), the application will abort as if it were an E_ERROR.
8192 E_DEPRECATED (integer) Runtime deprecation notices. Enable to receive notices about code that will not work in future versions.
16384 E_USER_DEPRECATED (integer) User-generated deprecation notices. Similar to E_DEPRECATED, except generated by PHP code using the trigger_error() function.
32767 E_ALL (integer) All supported errors and warnings, except for E_STRICT level before PHP 5.4.0.

Errors that are reported and those that are ignored are controlled by the error_reporting directive in php.ini.

Sometimes error reporting might be disabled, so this is something to keep in mind. If error reporting is disabled, placing the following code at the beginning can be a solution to view errors if you cannot enable error notifications.

<?php
error_reporting(E_ALL); 
ini_set("display_errors", 1); 
?>

You might sometimes want to create error logs in PHP.


In these situations, if you want to create error logs using the tools provided by the language, you can use the functions set_error_handler and error_log.

With set_error_handler, you can define which function you want to run for error handling, and with error_log, you can save the error to a file.

// Definir una función de manejo de errores personalizada
function fErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "Error [$errno]: $errstr in $errfile on line $errline";
}

// Establecer la función de manejo de errores personalizada
set_error_handler("fErrorHandler");

This is just an example of using the function, but you can combine it with the error_log function to save the error to a file.

// Definir una función de manejo de errores personalizada
function fErrorHandler($errno, $errstr, $errfile, $errline) {
    // Construir el mensaje de error
    $errorMessage = "Error [$errno]: $errstr in $errfile on line $errline";

    // Guardar el mensaje de error en un archivo de registro
    error_log($errorMessage . PHP_EOL, 3, "errores_en_programa.txt");
}

// Establecer la función de manejo de errores personalizada
set_error_handler("fErrorHandler");

Errors logs with PHP.ini

Another way to have error logs is by enabling this function in php.ini, although it’s quite basic compared to using the set_error_handler function.

You can do something like this:

php.ini
log_errors = On;
display_errors = Off;
error_log = /path_to_errorlog/errors.log;

When you do this, it’s not necessary to use the error_log function, but you can use it in specific cases where the error needs to be customized.

Monolog

You can also use Monolog for error handling, which is a popular third-party library in PHP and is well-maintained.

Monolog sends your logs to files, sockets, inboxes, databases, and various web services. Special handlers allow you to build advanced logging strategies.

https://github.com/Seldaek/monolog

You can install Monolog using Composer with the command: composer require monolog/monolog

An example provided on the Monolog GitHub page:

<?php

use Monolog\Level;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Level::Warning));

// add records to the log
$log->warning('Foo');
$log->error('Bar');

In theory, Monolog would work as follows, and I say “would work” because I’m not familiar with Monolog. See the following code:

2 canales
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Crear un nuevo logger (canal) para errores
$errorLogger = new Logger('error_logger');
$errorLogger->pushHandler(new StreamHandler('/path/to/error.log', Logger::ERROR));

// Crear un nuevo logger (canal) para advertencias
$warningLogger = new Logger('warning_logger');
$warningLogger->pushHandler(new StreamHandler('/path/to/warning.log', Logger::WARNING));

// Ejemplo de uso: registrar un mensaje de error
$errorLogger->error('Este es un mensaje de error.');

// Ejemplo de uso: registrar una advertencia
$warningLogger->warning('Esta es una advertencia.');

See that I create 2 channels, one for errors and one for warnings (advertisements).

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category