Jas*_*ker 110 php error-handling exception-handling exception
也许我在PHP手册的某个地方遗漏了它,但是错误和异常之间究竟有什么区别?我能看到的唯一区别是错误和异常的处理方式不同.但是什么导致异常以及导致错误的原因是什么?
gna*_*arf 83
异常抛出 -它们的目的是捕获.错误通常是不可恢复的.让我们举个例子 - 你有一个代码块可以将一行插入数据库.此调用可能失败(重复ID) - 您将需要一个"错误",在这种情况下是"异常".当您插入这些行时,您可以执行类似的操作
try {
$row->insert();
$inserted = true;
} catch (Exception $e) {
echo "There was an error inserting the row - ".$e->getMessage();
$inserted = false;
}
echo "Some more stuff";
Run Code Online (Sandbox Code Playgroud)
程序执行将继续 - 因为你'抓住'了例外.除非被捕获,否则异常将被视为错误.它允许您在失败后继续执行程序.
Kri*_*ris 54
我通常set_error_handler使用一个函数来获取错误并抛出一个异常,这样无论发生什么,我都会有异常来处理.没有更好的@file_get_contents和整洁的尝试/捕获.
在调试情况下,我还有一个异常处理程序,可以输出类似asp.net的页面.我在路上发布这个但是如果要求我会稍后发布示例源.
编辑:
按照承诺,我已经将我的一些代码剪切并粘贴在一起制作样本.我已将下面的文件保存到我的工作站上,你可以不再看到这里的结果(因为链接已损坏).
<?php
define( 'DEBUG', true );
class ErrorOrWarningException extends Exception
{
protected $_Context = null;
public function getContext()
{
return $this->_Context;
}
public function setContext( $value )
{
$this->_Context = $value;
}
public function __construct( $code, $message, $file, $line, $context )
{
parent::__construct( $message, $code );
$this->file = $file;
$this->line = $line;
$this->setContext( $context );
}
}
/**
* Inspire to write perfect code. everything is an exception, even minor warnings.
**/
function error_to_exception( $code, $message, $file, $line, $context )
{
throw new ErrorOrWarningException( $code, $message, $file, $line, $context );
}
set_error_handler( 'error_to_exception' );
function global_exception_handler( $ex )
{
ob_start();
dump_exception( $ex );
$dump = ob_get_clean();
// send email of dump to administrator?...
// if we are in debug mode we are allowed to dump exceptions to the browser.
if ( defined( 'DEBUG' ) && DEBUG == true )
{
echo $dump;
}
else // if we are in production we give our visitor a nice message without all the details.
{
echo file_get_contents( 'static/errors/fatalexception.html' );
}
exit;
}
function dump_exception( Exception $ex )
{
$file = $ex->getFile();
$line = $ex->getLine();
if ( file_exists( $file ) )
{
$lines = file( $file );
}
?><html>
<head>
<title><?= $ex->getMessage(); ?></title>
<style type="text/css">
body {
width : 800px;
margin : auto;
}
ul.code {
border : inset 1px;
}
ul.code li {
white-space: pre ;
list-style-type : none;
font-family : monospace;
}
ul.code li.line {
color : red;
}
table.trace {
width : 100%;
border-collapse : collapse;
border : solid 1px black;
}
table.thead tr {
background : rgb(240,240,240);
}
table.trace tr.odd {
background : white;
}
table.trace tr.even {
background : rgb(250,250,250);
}
table.trace td {
padding : 2px 4px 2px 4px;
}
</style>
</head>
<body>
<h1>Uncaught <?= get_class( $ex ); ?></h1>
<h2><?= $ex->getMessage(); ?></h2>
<p>
An uncaught <?= get_class( $ex ); ?> was thrown on line <?= $line; ?> of file <?= basename( $file ); ?> that prevented further execution of this request.
</p>
<h2>Where it happened:</h2>
<? if ( isset($lines) ) : ?>
<code><?= $file; ?></code>
<ul class="code">
<? for( $i = $line - 3; $i < $line + 3; $i ++ ) : ?>
<? if ( $i > 0 && $i < count( $lines ) ) : ?>
<? if ( $i == $line-1 ) : ?>
<li class="line"><?= str_replace( "\n", "", $lines[$i] ); ?></li>
<? else : ?>
<li><?= str_replace( "\n", "", $lines[$i] ); ?></li>
<? endif; ?>
<? endif; ?>
<? endfor; ?>
</ul>
<? endif; ?>
<? if ( is_array( $ex->getTrace() ) ) : ?>
<h2>Stack trace:</h2>
<table class="trace">
<thead>
<tr>
<td>File</td>
<td>Line</td>
<td>Class</td>
<td>Function</td>
<td>Arguments</td>
</tr>
</thead>
<tbody>
<? foreach ( $ex->getTrace() as $i => $trace ) : ?>
<tr class="<?= $i % 2 == 0 ? 'even' : 'odd'; ?>">
<td><?= isset($trace[ 'file' ]) ? basename($trace[ 'file' ]) : ''; ?></td>
<td><?= isset($trace[ 'line' ]) ? $trace[ 'line' ] : ''; ?></td>
<td><?= isset($trace[ 'class' ]) ? $trace[ 'class' ] : ''; ?></td>
<td><?= isset($trace[ 'function' ]) ? $trace[ 'function' ] : ''; ?></td>
<td>
<? if( isset($trace[ 'args' ]) ) : ?>
<? foreach ( $trace[ 'args' ] as $i => $arg ) : ?>
<span title="<?= var_export( $arg, true ); ?>"><?= gettype( $arg ); ?></span>
<?= $i < count( $trace['args'] ) -1 ? ',' : ''; ?>
<? endforeach; ?>
<? else : ?>
NULL
<? endif; ?>
</td>
</tr>
<? endforeach;?>
</tbody>
</table>
<? else : ?>
<pre><?= $ex->getTraceAsString(); ?></pre>
<? endif; ?>
</body>
</html><? // back in php
}
set_exception_handler( 'global_exception_handler' );
class X
{
function __construct()
{
trigger_error( 'Whoops!', E_USER_NOTICE );
}
}
$x = new X();
throw new Exception( 'Execution will never get here' );
?>
Run Code Online (Sandbox Code Playgroud)
Art*_*dez 15
答案值得谈论房间里的大象
错误是在运行时处理错误条件的旧方法.通常,代码会set_error_handler在执行某些代码之前调用类似的东西.遵循汇编语言中断的传统.以下是一些BASIC代码的外观.
on error :divide_error
print 1/0
print "this won't print"
:divide_error
if errcode = X
print "divide by zero error"
Run Code Online (Sandbox Code Playgroud)
很难确保set_error_handler用正确的值调用它.更糟糕的是,可以调用一个单独的过程来改变错误处理程序.此外,很多次电话都穿插着set_error_handler电话和处理程序.代码很容易快速失控.异常处理通过形式化良好代码实际执行的语法和语义来解决问题.
try {
print 1/0;
print "this won't print";
} catch (DivideByZeroException $e) {
print "divide by zero error";
}
Run Code Online (Sandbox Code Playgroud)
没有单独的功能或调用错误的错误处理程序的风险.现在代码保证在同一个地方.另外,我们得到更好的错误消息
PHP曾经只有错误处理,当许多其他语言已经演变为更好的异常处理模型.最终,PHP的制造商实现了异常处理.但是可能支持旧代码,它们保持错误处理并提供了一种使错误处理看起来像异常处理的方法.除此之外,无法保证某些代码可能无法重置错误处理程序,这正是异常处理所要提供的.
最后的答案
在实现异常处理之前编码的错误可能仍然是错误.新错误可能是例外.但是没有设计或逻辑是错误,哪些是例外.它只是基于编码时可用的内容,以及程序员编码的偏好.
这里要添加的一件事是关于处理异常和错误.出于应用程序开发人员的目的,错误和异常都是您要记录的"坏事",以了解您的应用程序所遇到的问题 - 从而使您的客户从长远来看具有更好的体验.
因此,编写一个与异常操作相同的错误处理程序是有意义的.
如其他答案所述,将异常thrower的错误处理程序设置为处理PHP错误的最佳方法.我使用了一点简单的设置:
set_error_handler(function ($errno, $errstr, $errfile, $errline ) {
if (error_reporting()) {
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
}
});
Run Code Online (Sandbox Code Playgroud)
请注意error_reporting()检查以保持@操作员的工作.此外,没有必要定义自定义异常,PHP有一个很好的类.
抛出异常的好处是异常具有与它们相关联的堆栈跟踪,因此很容易找到问题所在.
回复:“但是错误和异常之间究竟有什么区别?”
关于这里的差异有很多很好的答案。我将添加一些尚未讨论的内容 - 性能。具体来说,这是抛出/处理异常和处理返回码(成功或某些错误)之间的区别。通常,在 php 中,这意味着返回falseor null,但它们可以更详细,例如文件上传:http : //php.net/manual/en/features.file-upload.errors.php你甚至可以返回一个 Exception 对象!
我已经用不同的语言/系统完成了一些性能测试。一般来说,异常处理比检查错误返回码慢大约 10,000 倍。
所以,如果它绝对、肯定需要在它开始之前完成执行——好吧,你运气不好,因为时间旅行不存在。如果没有时间旅行,返回代码是可用的最快选项。
编辑:
PHP 针对异常处理进行了高度优化。实际测试表明,抛出异常仅比返回值慢 2-10 倍。