我正在尝试向我们的错误记录器发送一条特定的错误消息,该消息涉及特定发生的错误的上下文,因为传递给
array_key_exists
的变量不是数组。我想在我的错误消息中非常具体,所以我想要一个 catch
仅当发生特定的 $x is not an array
异常时才专门返回有关上下文的一些信息,但我不知道如何专门查找该异常例外,有办法吗?
例如,我有:
try {
// blah blah some stuff
array_key_exists('blah', $maybeAnArray)
// blah blah more stuff
} catch ( Exception $e ) {
logger()->error($e);
// send notification that says $maybeAnArray is not an array because of blah blah, do something about it when you see this error
}
仅在上述情况下,
Exception $e
才会被捕获为任何异常,而不仅仅是数组异常。
有没有办法像使用 if 语句那样做一些事情,你可以做这样的事情:
if(!is_array($maybeAnArray) {
// throw Exception $e and log error with specific details
}
谢谢!
这是您想要实现的目标的一个工作示例。
<?php
// Simulate a logger function
function logger() {
return new class {
public function error($message) {
echo "Logged Error: " . $message . "\n";
}
};
}
// Example function to demonstrate error handling
function checkArrayKey($maybeAnArray) {
try {
// Trying to use array_key_exists with $maybeAnArray
array_key_exists('blah', $maybeAnArray);
echo "array_key_exists executed successfully.\n";
} catch (TypeError $e) {
// Specific handling for when $maybeAnArray is not an array
logger()->error("TypeError: \$maybeAnArray is not an array. Value: " . print_r($maybeAnArray, true));
// You could do further processing or notification here
} catch (Exception $e) {
// Generic handling for other exceptions
logger()->error("General Exception: " . $e->getMessage());
}
}
// Test cases
$validArray = ['blah' => 'value'];
$invalidValue = "This is not an array";
$anotherInvalidValue = 12345;
// Calling the function with different types of inputs
echo "Test Case 1: Valid Array\n";
checkArrayKey($validArray); // Should execute without any errors
echo "\nTest Case 2: Invalid Value (String)\n";
checkArrayKey($invalidValue); // Should catch TypeError and log a specific message
echo "\nTest Case 3: Invalid Value (Integer)\n";
checkArrayKey($anotherInvalidValue); // Should catch TypeError and log a specific message
?>
对于 cli 测试,您可以使用这个衬垫:
php -r 'function logger() { return new class { public function error($message) { echo "Logged Error: " . $message . "\n"; } }; } function checkArrayKey($maybeAnArray) { try { array_key_exists("blah", $maybeAnArray); echo "array_key_exists executed successfully.\n"; } catch (TypeError $e) { logger()->error("TypeError: \$maybeAnArray is not an array. Value: " . print_r($maybeAnArray, true)); } catch (Exception $e) { logger()->error("General Exception: " . $e->getMessage()); } } echo "Test Case 1: Valid Array\n"; checkArrayKey(["blah" => "value"]); echo "\nTest Case 2: Invalid Value (String)\n"; checkArrayKey("This is not an array"); echo "\nTest Case 3: Invalid Value (Integer)\n"; checkArrayKey(12345);'