diff --git a/src/ValueAs.php b/src/ValueAs.php index 6be7a7f..45407ec 100644 --- a/src/ValueAs.php +++ b/src/ValueAs.php @@ -280,4 +280,24 @@ public static function transformed($value, callable $callback, $default = null) { return $value ? self::coalesce($callback($value), $default) : $default; } + + /** + * Call a callable, catching any exception and returning default + * + * @param callable $callable + * @param mixed $default + * + * @return mixed + */ + public static function caught(callable $callable, $default = null) + { + try + { + return $callable(); + } + catch(\Exception $e) + { + return is_callable($default) ? $default($e) : $default; + } + } } diff --git a/tests/ValueAsTest.php b/tests/ValueAsTest.php index 0e209f3..9ca4735 100644 --- a/tests/ValueAsTest.php +++ b/tests/ValueAsTest.php @@ -166,4 +166,17 @@ public function testTransformed() $this->assertEquals('ab', ValueAs::transformed('1', $callback, 'ab')); $this->assertEquals('ab', ValueAs::transformed(null, $callback, 'ab')); } + + public function testCaught() + { + $this->assertEquals('abc', ValueAs::caught(function () { throw new \Exception('e'); }, 'abc')); + $this->assertEquals( + 'abcdef', + ValueAs::caught( + function () { throw new \Exception('abc'); }, + function (\Exception $e) { return $e->getMessage() . 'def'; } + ) + ); + $this->assertEquals('xyz', ValueAs::caught(function () { return 'xyz'; }, 'abc')); + } }