Sunteți pe pagina 1din 10

Downloads

Documentation
Get Involved
Help

Search

Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers

Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection
DTrace Dynamic Tracing

Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Credit Card Processing
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions

Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
Previous man page
gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box

ErrorException::__construct
Exception::__clone

Manual de PHP
Referencia del lenguaje
Excepciones predefinidas

Change language: Spanish

Edit Report a Bug

ErrorException
(PHP 5 >= 5.1.0, PHP 7)

Introduccin
Una excepcin de error.

Sinopsis de la Clase
ErrorException extends Exception {
/* Propiedades */
protected int $severity ;
/* Propiedades heredadas */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Mtodos */
public __construct ([ string $message = "" [, int $code = 0 [, int $severity = E_ERROR [, string
$filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )
final public int getSeverity ( void )
/* Mtodos heredados */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Propiedades
severity
La gravedad de la excepcin

Ejemplos
Ejemplo #1 Utilizar set_error_handler() para convertir mensajes de error en
objetos ErrorException.

<?php
functionexception_error_handler($severidad,$mensaje,$fichero,$lnea){
if(!(error_reporting()&$severidad)){
//Estecdigodeerrornoestincluidoenerror_reporting
return;
}
thrownewErrorException($mensaje,0,$severidad,$fichero,$lnea);
}
set_error_handler("exception_error_handler");

/*Desencadenarlaexcepcin*/
strpos();
?>

El resultado del ejemplo sera algo similar a:


Fatal error: Uncaught exception 'ErrorException' with message 'strpos() expects at least 2 parameters, 0 given' i
Stack trace:
#0 [internal function]: exception_error_handler(2, 'strpos() expect...', '/home/bjori/php...', 12, Array)
#1 /home/bjori/php/cleandocs/test.php(12): strpos()
#2 {main}
thrown in /home/bjori/tmp/ex.php on line 12

Tabla de contenidos
ErrorException::__construct Constructor de la excepcin
ErrorException::getSeverity Obtiene la severidad de la excepcin

add a note

User Contributed Notes 4 notes

up
down
10
triplepoint at gmail dot com
7 years ago
As noted below, it's important to realize that unless caught, any Exception thrown will halt the
script. So converting EVERY notice, warning, or error to an ErrorException will halt your script
when something harmlesss like E_USER_NOTICE is triggered.

It seems to me the best use of the ErrorException class is something like this:

<?php
function custom_error_handler($number, $string, $file, $line, $context)
{
// Determine if this error is one of the enabled ones in php config (php.ini, .htaccess, etc)
$error_is_enabled = (bool)($number & ini_get('error_reporting') );

// -- FATAL ERROR
// throw an Error Exception, to be handled by whatever Exception handling logic is available in
this context
if( in_array($number, array(E_USER_ERROR, E_RECOVERABLE_ERROR)) && $error_is_enabled ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

// -- NON-FATAL ERROR/WARNING/NOTICE
// Log the error if it's enabled, otherwise just ignore it
else if( $error_is_enabled ) {
error_log( $string, 0 );
return false; // Make sure this ends up in $php_errormsg, if appropriate
}
}
?>

Setting this function as the error handler will result in ErrorExceptions only being thrown for
E_USER_ERROR and E_RECOVERABLE_ERROR, while other enabled error types will simply get error_log()'ed.

It's worth noting again that no matter what you do, "E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT" will never reach your custom error handler,
and therefore will not be converted into ErrorExceptions. Plan accordingly.
up
down
11
randallgirard at hotmail dot com
7 years ago
E_USER_WARNING, E_USER_NOTICE, and any other non-terminating error codes, are useless and act like
E_USER_ERROR (which terminate) when you combine a custom ERROR_HANDLER with ErrorException and do not
CATCH the error. There is NO way to return execution to the parent scope in the EXCEPTION_HANDLER.

<?php

error_reporting(E_ALL);
define('DEBUG', true);
define('LINEBREAK', "\r\n");

error::initiate('./error_backtrace.log');

try
trigger_error("First error", E_USER_NOTICE);
catch ( ErrorException $e )
print("Caught the error: ".$e->getMessage."<br />\r\n" );

trigger_error("This event WILL fire", E_USER_NOTICE);

trigger_error("This event will NOT fire", E_USER_NOTICE);

abstract class error {

public static $LIST = array();

private function __construct() {}

public static function initiate( $log = false ) {


set_error_handler( 'error::err_handler' );
set_exception_handler( 'error::exc_handler' );
if ( $log !== false ) {
if ( ! ini_get('log_errors') )
ini_set('log_errors', true);
if ( ! ini_get('error_log') )
ini_set('error_log', $log);
}
}

public static function err_handler($errno, $errstr, $errfile, $errline, $errcontext) {


$l = error_reporting();
if ( $l & $errno ) {

$exit = false;
switch ( $errno ) {
case E_USER_ERROR:
$type = 'Fatal Error';
$exit = true;
break;
case E_USER_WARNING:
case E_WARNING:
$type = 'Warning';
break;
case E_USER_NOTICE:
case E_NOTICE:
case @E_STRICT:
$type = 'Notice';
break;
case @E_RECOVERABLE_ERROR:
$type = 'Catchable';
break;
default:
$type = 'Unknown Error';
$exit = true;
break;
}

$exception = new \ErrorException($type.': '.$errstr, 0, $errno, $errfile, $errline);

if ( $exit ) {
exc_handler($exception);
exit();
}
else
throw $exception;
}
return false;
}

function exc_handler($exception) {
$log = $exception->getMessage() . "\n" . $exception->getTraceAsString() . LINEBREAK;
if ( ini_get('log_errors') )
error_log($log, 0);
print("Unhandled Exception" . (DEBUG ? " - $log" : ''));
}

}
?>
up
down
5
luke at cywh dot com
7 years ago
To add to the comments made by chris AT cmbuckley DOT co DOT uk about the ErrorException problem with
args:

I noticed that the problem is in the ErrorException class itself, not the Exception class. When using
just the exception class, it's no longer an issue. Besides the args problem, the only difference
between Exception and ErrorException in the stack trace is that the args are left out of the error
handler exception function. I'm not sure if this was on purpose or not, but it shouldn't hurt to show
this information anyway.

So instead of using this broken extended class, you can ignore it and make your own extended class
and avoid the problem all together:

<?php

header('Content-Type: text/plain');

class ErrorHandler extends Exception {


protected $severity;

public function __construct($message, $code, $severity, $filename, $lineno) {


$this->message = $message;
$this->code = $code;
$this->severity = $severity;
$this->file = $filename;
$this->line = $lineno;
}

public function getSeverity() {


return $this->severity;
}
}

function exception_error_handler($errno, $errstr, $errfile, $errline ) {


throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler", E_ALL);

function A() {
$foo->bar; // Purposely cause error
}

function B($c) {
A();
}
try {
B('foobar');
} catch (Exception $e) {
var_dump($e->getTrace());
}

?>

The only thing I wish I could do was remove the entry for the error handler function because it's
quite irrelevant. Maybe that's what they were trying to do with the ErrorException class? Either way,
you can't change it because the trace functions are final, and the variable is private.
up
down
-6
xianrenb at gmail dot com
4 years ago
add a note

Excepciones predefinidas
Exception
ErrorException
Error
ArithmeticError
AssertionError
DivisionByZeroError
ParseError
TypeError
Copyright 2001-2017 The PHP Group
My PHP.net
Contact
Other PHP.net sites
Mirror sites
Privacy policy

S-ar putea să vă placă și