From 824858c6b252cb7f01c1743d67809c595a66a619 Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Thu, 5 Nov 2015 12:20:02 -0800 Subject: [PATCH] Add convenience function for formatting NSError for reporting Reviewed By: nicklockwood Differential Revision: D2620933 fb-gh-sync-id: c5c40b78b19f12c9a3b1564b1e21f1acb12309ab --- React/Base/RCTAssert.h | 5 +++++ React/Base/RCTAssert.m | 31 ++++++++++++++++++------------- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/React/Base/RCTAssert.h b/React/Base/RCTAssert.h index 92cf1dae6..b109bf81a 100644 --- a/React/Base/RCTAssert.h +++ b/React/Base/RCTAssert.h @@ -107,6 +107,11 @@ RCT_EXTERN RCTFatalHandler RCTGetFatalHandler(void); */ RCT_EXTERN NSString *RCTCurrentThreadName(void); +/** + * Helper to get generate exception message from NSError + */ +RCT_EXTERN NSString *RCTFormatError(NSString *message, NSArray *stacktrace, NSUInteger maxMessageLength); + /** * Convenience macro to assert which thread is currently running (DEBUG mode only) */ diff --git a/React/Base/RCTAssert.m b/React/Base/RCTAssert.m index f28773ae5..872920834 100644 --- a/React/Base/RCTAssert.m +++ b/React/Base/RCTAssert.m @@ -124,22 +124,10 @@ void RCTFatal(NSError *error) if (fatalHandler) { fatalHandler(error); } else { - const NSUInteger maxMessageLength = 75; - NSString *message = [error localizedDescription]; - if (message.length > maxMessageLength) { - message = [[message substringToIndex:maxMessageLength] stringByAppendingString:@"..."]; - } - - NSMutableString *prettyStack = [NSMutableString stringWithString:@"\n"]; - if ([error.userInfo[RCTJSStackTraceKey] isKindOfClass:[NSArray class]]) { - for (NSDictionary *frame in error.userInfo[RCTJSStackTraceKey]) { - [prettyStack appendFormat:@"%@@%@:%@\n", frame[@"methodName"], frame[@"lineNumber"], frame[@"column"]]; - } - } - #if DEBUG @try { #endif + NSString *message = RCTFormatError([error localizedDescription], error.userInfo[RCTJSStackTraceKey], 75); [NSException raise:@"RCTFatalException" format:@"%@", message]; #if DEBUG } @catch (NSException *e) {} @@ -156,3 +144,20 @@ RCTFatalHandler RCTGetFatalHandler(void) { return RCTCurrentFatalHandler; } + +NSString *RCTFormatError(NSString *message, NSArray *stackTrace, NSUInteger maxMessageLength) +{ + if (maxMessageLength > 0 && message.length > maxMessageLength) { + message = [[message substringToIndex:maxMessageLength] stringByAppendingString:@"..."]; + } + + NSMutableString *prettyStack = [NSMutableString string]; + if (stackTrace) { + [prettyStack appendString:@", stack:\n"]; + for (NSDictionary *frame in stackTrace) { + [prettyStack appendFormat:@"%@@%@:%@\n", frame[@"methodName"], frame[@"lineNumber"], frame[@"column"]]; + } + } + + return [NSString stringWithFormat:@"Message: %@%@", message, prettyStack]; +}