提问人:hretic 提问时间:6/18/2023 更新时间:6/18/2023 访问量:124
检查对象是否为任何类型的异常
check if object is exception of any kind
问:
在我的 API 中,我有一个名为 ApiException 的自定义异常。我想将代码中的所有错误消息和异常传递给此自定义异常,以处理日志记录和响应返回。我在想这样的事情:
class ApiException extends Exception
{
public $data;
public $status;
public function __construct($data, $status = 400)
{
$this->data = $data;
$this->status = $status;
}
public function render()
{
$output = $this->getOutput();
return response()->json($output, $this->status);
}
private function getOutput()
{
if (is_object($this->data) && $this->data instanceof Exception) {
return $this->getOutputException();
} else if (is_string($this->data)) {
return $this->getOutputString();
} else {
return ['message' => $this->defaultMessage()];
}
}
private function getOutputException()
{
// log exception
// send notification
return ['message' => $this->data->getMessage()];
}
private function getOutputString()
{
return ['message' => $this->data];
}
private function defaultMessage()
{
return __('message.defaultErrorMessage');
}
}
我可能会用它来返回一个简单的字符串:
$resource = Resource::find($id);
if (!$resource)
throw new ApiException("resource not found!");
或者传递一般异常:
try {
Table::insert($data);
} catch (\Exception $exception) {
throw new ApiException($exception);
}
或任何其他例外情况:
$client = new GuzzleHttp\Client\Client();
try {
return $client->request('GET', "http://something");
} catch (GuzzleHttp\Exception\ClientException\ClientException $e) {
throw new ApiException($exception);
}
这是我有问题的地方:.is any kind of exception
private function getOutput()
{
if (is_object($this->data) && $this->data instanceof Exception) {
return $this->getOutputException();
}
}
如何检查我的对象是否为异常?我的意思是任何类型的例外,而不仅仅是一般的例外,比如.GuzzleHttp\Exception\ClientException\ClientException
答:
0赞
MadCatERZ
6/18/2023
#1
所有自定义异常都扩展 \Exception。试试这个:
$reflection = new \ReflectionClass($this->data);
if($reflection->isSubclassOf(Exception::class)) {
//$this->data is a subclass of Exception
}
或者,如您的代码中所示
if( $this->data instanceof Exception) {
echo "yes";
}
评论
$this->data instanceof Exception
this->data is any kind of exception
$this->data instanceof Exception