CErrorHandler组件中有一个属性$errorAction,当发生异常的时候,可以有$errorAction来对错误进行输出,
但是在这个action中如何拿到抛出异常的code($e->getCode())呢?
目前Yii::app()->errorHandler->error->code,这个错误码其实是http返回错误码,在大部分情况下都是500
(CErrorHandler.php的第141行: ‘code’=>($exception instanceof CHttpException)?$exception->statusCode:500)。
在开发过程中,不仅要获得错误消息($e->getMessage()),很多时候还是需要获得错误码的($e->getCode())。
Thanks!
我目前的处理办法是继承CErrorHandler类,重写了handleException方法,给成员变量$this->_error数组添加了一个表示异常类的错误码,具体如下:
class [size="3"]CErrorHandlerWeb[/size] extends CErrorHandler
{
/**
* Handles the exception.
* @param Exception the exception captured
*/
protected function handleException($exception)
{
$app=Yii::app();
if($app instanceof CWebApplication)
{
if(($trace=$this->getExactTrace($exception))===null)
{
$fileName=$exception->getFile();
$errorLine=$exception->getLine();
}
else
{
$fileName=$trace['file'];
$errorLine=$trace['line'];
}
$this->_error=$data=array(
'code'=>($exception instanceof CHttpException)?$exception->statusCode:500,
'type'=>get_class($exception),
[size="3"][b]'errorCode'=>$exception->getCode(), //获得异常类的错误号,只增加了这一行。[/b][/size]
'message'=>$exception->getMessage(),
'file'=>$fileName,
'line'=>$errorLine,
'trace'=>$exception->getTraceAsString(),
'source'=>$this->getSourceLines($fileName,$errorLine),
);
if(!headers_sent())
header("HTTP/1.0 {$data['code']} ".get_class($exception));
if($exception instanceof CHttpException || !YII_DEBUG)
$this->render('error',$data);
else
$this->render('exception',$data);
}
else
$app->displayException($exception);
}
}
非常感谢您的回复,
能不能这样命名:第一个code应该是http的返回码。
…
‘codeHttp’=>($exception instanceof CHttpException)?$exception->statusCode:500,
‘type’=>get_class($exception),
‘code’=>$exception->getCode(),
…