如何在PHP中获得多个错误处理程序?
我试过这个:如何在PHP中获得多个错误处理程序?,php,function,handler,Php,Function,Handler,我试过这个: set_error_handler('ReportError', E_NOTICE | E_USER_NOTICE); set_error_handler('ErrorHandler', E_ALL & ~(E_NOTICE | E_USER_NOTICE)); 但只有第二种方法有效。如何为不同类型的错误设置不同的错误处理程序?为什么不在处理程序中设置一个错误处理程序并按错误类型进行筛选,然后从中调用不同的函数?制作一个GenericErrorHandle
set_error_handler('ReportError', E_NOTICE | E_USER_NOTICE);
set_error_handler('ErrorHandler', E_ALL & ~(E_NOTICE | E_USER_NOTICE));
但只有第二种方法有效。如何为不同类型的错误设置不同的错误处理程序?为什么不在处理程序中设置一个错误处理程序并按错误类型进行筛选,然后从中调用不同的函数?制作一个
GenericErrorHandler()
并在其中执行以下操作:
switch($errno){
case E_USER_ERROR: UserErrorHandler(...); break;
}
您可以有一个错误处理程序,并像这样处理错误(好的,它是PHP5.3,但请原谅-稍微修改一下,它会正常工作) 如果确实必须使用两个不同的set\u error\u处理程序,那么可以使用函数调用来获取前面的错误处理程序。即使这样,您也会丢失正在筛选的错误
拥有这样的控制器要优雅得多。因此,要理解Westie所说的,重要的是您只能有一个错误处理程序,set_error_handler()函数返回先前定义的错误处理程序,如果没有定义,则返回null。因此,在错误处理程序中,在注册前一个错误处理程序时,可能使用一个存储前一个错误处理程序的类,以便在使用类方法处理错误时,也调用前一个错误处理程序。raven php Sentry客户端的摘录:
public function registerErrorHandler($call_existing_error_handler = true, $error_types = -1)
{
$this->error_types = $error_types;
$this->old_error_handler = set_error_handler(array($this, 'handleError'), error_reporting());
$this->call_existing_error_handler = $call_existing_error_handler;
}
然后是句柄错误方法:
public function handleError($code, $message, $file = '', $line = 0, $context=array())
{
if ($this->error_types & $code & error_reporting()) {
$e = new ErrorException($message, 0, $code, $file, $line);
$this->handleException($e, true, $context);
}
if ($this->call_existing_error_handler && $this->old_error_handler) {
call_user_func($this->old_error_handler, $code, $message, $file, $line, $context);
}
}
请注意,这假设>=PHP5.4
public function handleError($code, $message, $file = '', $line = 0, $context=array())
{
if ($this->error_types & $code & error_reporting()) {
$e = new ErrorException($message, 0, $code, $file, $line);
$this->handleException($e, true, $context);
}
if ($this->call_existing_error_handler && $this->old_error_handler) {
call_user_func($this->old_error_handler, $code, $message, $file, $line, $context);
}
}