react-native/React/Base/RCTJSCErrorHandling.mm
Kevin Cooper e443b7379e More verbose error messages for iOS
Summary:
Output the reason for the error when failing to load source code. This was a big help when trying to diagnose https://github.com/facebook/react-native/issues/13299.

~~Unfortunately there still seems to be no way to get the offending line number (because `loadError.userInfo[RCTJSStackTraceKey]` is empty), but this is good enough.~~

Before:

```
[warn][tid:com.facebook.react.JavaScript][RCTBatchedBridge.m:510] Failed to execute source code. Unhandled JS Exception: SyntaxError
```

After:

```
[warn][tid:com.facebook.react.JavaScript][RCTJSCErrorHandling.mm:30] Couldn't get stack trace for http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:81886
[warn][tid:com.facebook.react.JavaScript][RCTBatchedBridge.m:510] Failed to execute source code. Unhandled JS Exception: SyntaxError Unexpected keyword 'var'
```
Closes https://github.com/facebook/react-native/pull/13561

Differential Revision: D4908501

Pulled By: javache

fbshipit-source-id: a316dc70739b917b3cc690309d0ff37a8bb5d412
2017-04-18 14:19:13 -07:00

44 lines
1.7 KiB
Plaintext

/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "RCTJSCErrorHandling.h"
#import <jschelpers/JavaScriptCore.h>
#import "RCTAssert.h"
#import "RCTJSStackFrame.h"
#import "RCTLog.h"
NSString *const RCTJSExceptionUnsymbolicatedStackTraceKey = @"RCTJSExceptionUnsymbolicatedStackTraceKey";
NSError *RCTNSErrorFromJSError(JSValue *exception)
{
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"Unhandled JS Exception: %@", [exception[@"name"] toString] ?: @"Unknown"];
NSString *const exceptionMessage = [exception[@"message"] toString];
if ([exceptionMessage length]) {
userInfo[NSLocalizedFailureReasonErrorKey] = exceptionMessage;
}
NSString *const stack = [exception[@"stack"] toString];
if ([@"undefined" isEqualToString:stack]) {
RCTLogWarn(@"Couldn't get stack trace for %@:%@", exception[@"sourceURL"], exception[@"line"]);
} else if ([stack length]) {
NSArray<RCTJSStackFrame *> *const unsymbolicatedFrames = [RCTJSStackFrame stackFramesWithLines:stack];
userInfo[RCTJSStackTraceKey] = unsymbolicatedFrames;
}
return [NSError errorWithDomain:RCTErrorDomain code:1 userInfo:userInfo];
}
NSError *RCTNSErrorFromJSErrorRef(JSValueRef exceptionRef, JSGlobalContextRef ctx)
{
JSContext *context = [JSC_JSContext(ctx) contextWithJSGlobalContextRef:ctx];
JSValue *exception = [JSC_JSValue(ctx) valueWithJSValueRef:exceptionRef inContext:context];
return RCTNSErrorFromJSError(exception);
}