diff --git a/Foundation/CPException.j b/Foundation/CPException.j index be23f3d62..290d3a877 100755 --- a/Foundation/CPException.j +++ b/Foundation/CPException.j @@ -71,6 +71,22 @@ if (input == nil) [[self exceptionWithName:aName reason:aReason userInfo:nil] raise]; } +/*! + Raises an exception with a name and a formatted reason. + @param aName the name of the exception to raise + @param aFormat the reason for the exception in sprintf style + @param ... the arguments for the sprintf format +*/ ++ (void)raise:(CPString)aName format:(CPString)aFormat, ... +{ + if (!aFormat) + [CPException raise:CPInvalidArgumentException + reason:"raise:format: the format can't be 'nil'"]; + + var aReason = ObjectiveJ.sprintf.apply(this, Array.prototype.slice.call(arguments, 3)); + [[self exceptionWithName:aName reason:aReason userInfo:nil] raise]; +} + /*! Creates an exception with a name, reason and user info. @param aName the name of the exception diff --git a/Tests/Foundation/CPExceptionTest.j b/Tests/Foundation/CPExceptionTest.j index 9c038223d..810dacc20 100644 --- a/Tests/Foundation/CPExceptionTest.j +++ b/Tests/Foundation/CPExceptionTest.j @@ -27,6 +27,22 @@ [self assertThrows:function(){[CPException raise:@"CPGenericException" reason:@"Margins must be positive"];}]; } +- (void)testRaise_format_ +{ + var success = NO; + try + { + [CPException raise:CPGenericException format:@"Expected %.2f for %s", 0.789, "hello"]; + } + catch (anException) + { + success = YES; + [self assert:CPGenericException equals:[anException name]]; + [self assert:@"Expected 0.79 for hello" equals:[anException reason]]; + } + [self assertTrue:success]; +} + - (void)testName { [self assert:[exception name] equals:@"CPGenericException"];