PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Error Handling Functions> <Constantes predefinidas
Last updated: Fri, 22 Aug 2008

view this page in

Ejemplos

A continuación podemos apreciar un ejemplo del uso de las capacidades de gestión de errores que vienen con PHP. Definimos una función de manipulación de errores que registra la información en un archivo (usando un formato XML), y envía un correo electrónico al desarrollador en caso de que un error crítico en la lógica del software ocurra.

Example #1 Uso de gestión de errores en un script

<?php
// haremos nuestra propia manipulación de errores
error_reporting(0);

// función de gestión de errores definida por el usuario
function gestorDeErroresDeUsuario($num_err$mens_err$nombre_archivo,
                                  
$num_linea$vars)
{

    
// marca de fecha/hora para el registro de error
    
$dt date("Y-m-d H:i:s (T)");

    
// definir una matriz asociativa de cadenas de error
    // en realidad las únicas entradas que deberíamos
    // considerar son E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING y E_USER_NOTICE

    
$tipo_error = array (
                
E_ERROR              => 'Error',
                
E_WARNING            => 'Advertencia',
                
E_PARSE              => 'Error de Intérprete',
                
E_NOTICE             => 'Anotación',
                
E_CORE_ERROR         => 'Error de Núcleo',
                
E_CORE_WARNING       => 'Advertencia de Núcleo',
                
E_COMPILE_ERROR      => 'Error de Compilación',
                
E_COMPILE_WARNING    => 'Advertencia de Compilación',
                
E_USER_ERROR         => 'Error de Usuario',
                
E_USER_WARNING       => 'Advertencia de Usuario',
                
E_USER_NOTICE        => 'Anotación de Usuario',
                
E_STRICT             => 'Anotación de tiempo de ejecución',
                
E_RECOVERABLE_ERROR  => 'Error Fatal Atrapable'
                
);
    
// conjunto de errores de los cuales se almacenará un rastreo
    
$errores_de_usuario = array(E_USER_ERRORE_USER_WARNINGE_USER_NOTICE);

    
$err "<errorentry>\n";
    
$err .= "\t<datetime>" $dt "</datetime>\n";
    
$err .= "\t<errornum>" $num_err "</errornum>\n";
    
$err .= "\t<errortype>" $tipo_error[$num_err] . "</errortype>\n";
    
$err .= "\t<errormsg>" $mens_err "</errormsg>\n";
    
$err .= "\t<scriptname>" $nombre_archivo "</scriptname>\n";
    
$err .= "\t<scriptlinenum>" $num_linea "</scriptlinenum>\n";

    if (
in_array($num_err$errores_de_usuario)) {
        
$err .= "\t<vartrace>" wddx_serialize_value($vars"Variables") . "</vartrace>\n";
    }
    
$err .= "</errorentry>\n\n";

    
// para efectos de depuración
    // echo $err;

    // guardar en el registro de errores, y enviar un correo
    // electrónico si hay un error crítico de usuario
    
error_log($err3"/usr/local/php4/error.log");
    if (
$num_err == E_USER_ERROR) {
        
mail("phpdev@example.com""Error Crítico de Usuario"$err);
    }
}


function 
distancia($vect1$vect2)
{
    if (!
is_array($vect1) || !is_array($vect2)) {
        
trigger_error("Parámetros incorrectos, se esperan matrices"E_USER_ERROR);
        return 
NULL;
    }

    if (
count($vect1) != count($vect2)) {
        
trigger_error("Los vectores deben ser del mismo tamaño"E_USER_ERROR);
        return 
NULL;
    }

    for (
$i=0$i<count($vect1); $i++) {
        
$c1 $vect1[$i]; $c2 $vect2[$i];
        
$d 0.0;
        if (!
is_numeric($c1)) {
            
trigger_error("La coordenada $i en el vector 1 no es un ".
                          
"número, se usará cero",
                            
E_USER_WARNING);
            
$c1 0.0;
        }
        if (!
is_numeric($c2)) {
            
trigger_error("La coordenada $i en el vector 2 no es un".
                          
"número, se usará cero",
                            
E_USER_WARNING);
            
$c2 0.0;
        }
        
$d += $c2*$c2 $c1*$c1;
    }
    return 
sqrt($d);
}

$gestor_de_errores_anterior set_error_handler("gestorDeErroresDeUsuario");

// constante indefinida, se genera una advertencia
$t NO_ESTOY_DEFINIDA;

// definir algunos "vectores"
$a = array(23"foo");
$b = array(5.54.3, -1.6);
$c = array(1, -3);

// generar un error de usuario
$t1 distance($c$b) . "\n";

// generar otro error de usuario
$t2 distance($b"no soy una matriz") . "\n";

// generar una advertencia
$t3 distance($a$b) . "\n";

?>



add a note add a note User Contributed Notes
Ejemplos
KBurkholder at EarthAsylum dot com
30-Jun-2008 05:29
Providing an example...

eac_error.class is a PHP static utility class for error handling. It is intended to be used throughout the PHP application for capture and reporting of errors and exceptions.

The error handling routine in eac_error.class is designed to provide detailed state information for the developer or administrator while still maintaining a secure environment. Error messages are only presented to the web user on true error conditions and do not include information that may be used to compromise the system. Notifications are sent to the webmaster/administrator in an encrypted state (using GnuPG) so that critical, private information cannot be intercepted in transit.

Features

GnuPG encrypted email sent to the web administrator.
Detailed system information included with email.
Function and class trace back information included.
Log errors to a single file or multiple files based on severity (fatal, error, warning ,notice).
Send email notice for each error or for all errors at the end of script execution.
Suppress or allow options (email, display, logging, etc.) when error is triggered.
Provide a program-designated error code with the error message.
Set a callback function to display errors and abort processing.
Include user-defined data in the error notification email.
Error condition detectable by AJAX and CURL.

http://www.kevinburkholder.com/sw_error.php

Error Handling Functions> <Constantes predefinidas
Last updated: Fri, 22 Aug 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites