当我在php中捕获一个异常并尝试输出一些细节时,getMessage()总是不返回任何内容。如果执行var_dump(),就会看到想要显示的消息。我做错了什么?
try
{
...
}
catch (Exception $e)
{
echo "<p>Exception: " . $e->getMessage() . "</p>";
return;
}
如果执行var_dump($e),将得到以下输出:
object(ETWSException)#735 (10) {["errorCode":protected]=> int(401)[" errorMessage":保护]=>字符串(226)"HTTP/1.1 401未授权日期:星期五,2015年8月21日18:26:30 GMT服务器:Apache WWW-Authenticate:OAuth领域= https://etws.etrade.com/, oauth_problem = token_expiredContent-Type: text/html;charset=utf-8 "["httpCode":protected]=> NULL ["message":protected]=> string(0)""【"字符串":"异常":私人]=>字符串(0)"("代码":保护)=>int(0)("文件":保护)=>[剪!)
我认为getMessage()应该显示errorMessage的内容。
嗯,我尝试了$e->getErrorMessage()和, 显示预期的消息。搜索谷歌php异常getErrorMessage似乎没有显示任何有用的(所有页面似乎只提到getMessage,而不是getErrorMessage)。到底发生了什么事?
电子贸易例外类是一个烂摊子。它实现了自己的构造函数,并且没有为标准Exception
设置正确的值。它期望您使用$e->getErrorMessage()
来获取消息。
<?php
/**
* E*TRADE PHP SDK
*
* @package PHP-SDK
* @version 1.1
* @copyright Copyright (c) 2012 E*TRADE FINANCIAL Corp.
*
*/
class ETWSException extends Exception
{
protected $errorCode;
protected $errorMessage;
protected $httpCode;
/**
* Constructor ETWSException
*
*/
public function __construct($errorMessage, $errorCode = null, $httpCode = null, Exception $previous = null) {
$this->errorMessage = $errorMessage;
$this->errorCode = $errorCode;
$this->httpCode = $httpCode;
}
/**
* Gets the value of the errorCode property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public function getErrorCode() {
return $this->errorCode;
}
/**
* Gets the value of the errorMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public function getErrorMessage() {
return $this->errorMessage;
}
/**
* Gets the value of the httpStatusCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public function getHttpCode() {
return $this->httpCode;
}
}
?>
这里有几个问题。首先,如果查看$e的var_dump,消息索引为空。因此,当您使用getMessage时,您将一无所获。其次,抛出的异常不是标准的PHP异常。它是由你正在使用的API编写的,你需要阅读它的文档来弄清楚如何正确处理异常。
["message":protected]=> string(0) ""
是你的问题
get_class_methods($e)
可能会暴露更多