¿Puedo coger la salida () y die () mensajes?
Pregunta
Me gustaría ser capaz de captar los mensajes die()
y exit()
. es posible? Estoy esperando por algo similar a set_error_handler
y set_exception_handler
. He mirado en register_shutdown_function()
pero parece que no contienen ningún contexto para los die()
y exit()
llamadas ofensivos.
Me da cuenta de que die()
y exit()
son malas maneras de manejar los errores. No estoy buscando que se les diga que no lo hiciera. :) Estoy creando un sistema genérico y quiero ser capaz de conectarse con gracia y exit()
die()
si por alguna razón alguien (no me) decide que esto es una idea buena de hacer.
Solución 4
Lo mejor que puedo decir que esto no es realmente posible. Algunas de las soluciones incluidas en este documento pueden trabajar pero requieren mucho trabajo adicional o muchas dependencias. No hay ninguna manera de forma fácil y fiable trampa de la matriz () y salida () mensajes.
Otros consejos
Sí se puede, pero se necesita ob_start , ob_get_contents , ob_end_clean y register_shutdown_function
function onDie(){
$message = ob_get_contents(); // Capture 'Doh'
ob_end_clean(); // Cleans output buffer
callWhateverYouWant();
}
register_shutdown_function('onDie');
//...
ob_start(); // You need this to turn on output buffering before using die/exit
@$dumbVar = 1000/0 or die('Doh'); // "@" prevent warning/error from php
//...
ob_end_clean(); // Remember clean your buffer before you need to use echo/print
De acuerdo con el manual PHP , funciones de apagado todavía debe ser notificada cuando die () o de salida () se llama.
funciones de apagado y noreferrer destructores de objetos siempre se ejecutarán incluso si la salida ( ) se llama.
No parece ser posible para obtener el estado enviado en salida ($ status). A menos que se puede usar búferes de salida para capturarlo, pero no estoy seguro de cómo sabría cuándo llamar ob_start()
.
override_function () podría ser interesante, si está disponible APD
¿Por qué no usar el manejo de error personalizado en su lugar? Si no, siempre se puede utilizar LD_PRELOAD y la inyección de código C para cogerlo :) o PHP recompilación con las personalizaciones: P
Si utiliza el único punto de método de entrada. (Index.php) se lo recomiendo esto para su gestión de errores:
versión corta:
ob_start();
register_shutdown_function('shutdownHandler');
include('something');
define(CLEAN_EXIT, true);
function shutdownHandler() {
if(!defined("CLEAN_EXIT") || !CLEAN_EXIT) {
$msg = "Script stopped unexpectedly: ".ob_get_contents();
//Handle premature die()/exit() here
}
}
pasos adicional y más detallada:
A grandes rasgos mi manera de hacerlo. aún más He pasando de lo que muestro aquí (manejo de transacciones de bases de datos / rollback / envío de correos electrónicos / escritura de registros / mostrar mensajes de error / reporte de errores de usuario / etc), pero esta es la idea básica detrás de todo ello). < br> Espero que ayuda a alguien.
<?php
//Some initialization
//starting output buffering. (fatalErrorHandler is optional, but I recommend using it)
ob_start('fatalErrorHandler');
//Execute code right at the end. Catch exit() and die() here. But also all other terminations inside PHPs control
register_shutdown_function('shutdownHandler');
//handling other errors: Also optional
set_error_handler('errorHandler');
try {
//Include of offensive code
include(...);
}
catch (Exception $ex) {
//Handling exception. Be careful to not raise exceptions here again. As you can end up in a cycle.
}
//Code reached this point, so it was a clean exit.
define(CLEAN_EXIT, true);
//Gets called when the script engine shuts down.
function shutdownHandler() {
$status = connection_status();
$statusText = "";
switch ($status) {
case 0:
if (!defined("CLEAN_EXIT") || !CLEAN_EXIT) {
$msg = "Script stopped unexpectedly: ".ob_get_contents();
//Handle premature die()/exit() here
}
else {
//Clean exit. Just return
return;
}
case 1: $statusText = "ABORTED (1)"; break;
case 2: $statusText = "TIMEOUT (2)"; break;
case 3: $statusText = "ABORTED & TIMEOUT (3)"; break;
default : $statusText = "UNKNOWN ($status)"; break;
}
//Handle other exit variants saved in $statusText here ob_get_contents() can have additional useful information here
}
// error handler function (This is optional in your case)
function errorHandler($errno, $errstr, $errfile, $errline) {
$msg = "[$errno] $errstr\nOn line $errline in file $errfile";
switch ($errno) {
case E_ERROR: $msg = "[E_ERROR] ".$msg; break;
case E_WARNING: $msg = "[E_WARNING] ".$msg; break;
case E_PARSE: $msg = "[E_PARSE] ".$msg; break;
case E_NOTICE: $msg = "[E_NOTICE] ".$msg; break;
case E_CORE_ERROR: $msg = "[E_CORE_ERROR] ".$msg; break;
case E_CORE_WARNING: $msg = "[E_CORE_WARNING] ".$msg; break;
case E_COMPILE_ERROR: $msg = "[E_COMPILE_ERROR] ".$msg; break;
case E_COMPILE_WARNING: $msg = "[E_COMPILE_WARNING] ".$msg; break;
case E_USER_ERROR: $msg = "[E_USER_ERROR] ".$msg; break;
case E_USER_WARNING: $msg = "[E_USER_WARNING] ".$msg; break;
case E_USER_NOTICE: $msg = "[E_USER_NOTICE] ".$msg; break;
case E_STRICT: $msg = "[E_STRICT] ".$msg; break;
case E_RECOVERABLE_ERROR: $msg = "[E_RECOVERABLE_ERROR] ".$msg; break;
case E_DEPRECATED: $msg = "[E_DEPRECIATED] ".$msg; break;
case E_USER_DEPRICIATED: $msg = "[E_USER_DEPRICIATED] ".$msg; break;
default: $msg = "[UNKNOWN] ".$msg; break;
}
//Handle Normal error/notice/warning here.
$handled = ...
if ($handled)
return true; //handled. Proceed execution
else
throw Exception($msg); //Be careful. this might quickly become cyclic. Be sure to have code that catches and handles exceptions. Else die() here after logging/reporting the error.
}
function fatalErrorHandler(&$buffer) {
$matches = null;
//Checking if the output contains a fatal error
if (preg_match('/<br \/>\s*<b>([^<>].*)error<\/b>:(.*)<br \/>$/', $buffer, $matches) ) {
$msg = preg_replace('/<.*?>/','',$matches[2]);
//Handle Fatal error here
return "There was an unexpected situation that resulted in an error. We have been informed and will look into it."
}
//No fatal exception. Return buffer and continue
return $buffer;
}
Sí:. Escribir una función y utilice en su lugar
function kill($msg){
// Do your logging..
exit($msg);
}