Skip to content

Convert JavaScript uncaught exception stack traces to Dart stacks #1603

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 3 commits into from
May 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dwds/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## 14.0.3-dev
- Update `package:vm_service` to 8.3.0.
- Convert JavaScript stack traces in uncaught exceptions to Dart stack traces.

## 14.0.2
- Update the min SDK constraint to 2.17.0.
Expand Down
6 changes: 4 additions & 2 deletions dwds/lib/src/debugging/debugger.dart
Original file line number Diff line number Diff line change
Expand Up @@ -558,8 +558,10 @@ class Debugger extends Domain {
if (isNativeJsObject(exception)) {
if (obj.description != null) {
// Create a string exception object.
exception = await inspector.instanceHelper
.instanceRefFor(obj.description);
var description =
await inspector.mapExceptionStackTrace(obj.description);
exception =
await inspector.instanceHelper.instanceRefFor(description);
} else {
exception = null;
}
Expand Down
27 changes: 26 additions & 1 deletion dwds/lib/src/debugging/inspector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ class AppInspector extends Domain {
final String _root;
final SdkConfiguration _sdkConfiguration;

/// JavaScript expression that evaluates to the Dart stack trace mapper.
static const stackTraceMapperExpression = '\$dartStackTraceUtility.mapper';

/// Regex used to extract the message from an exception description.
static final exceptionMessageRegex = RegExp(r'^.*$', multiLine: true);

AppInspector._(
this.appConnection,
this.isolate,
Expand Down Expand Up @@ -223,7 +229,7 @@ class AppInspector extends Domain {
/// [evalExpression] should be a JS function definition that can accept
/// [arguments].
Future<RemoteObject> _jsCallFunction(
String evalExpression, List<RemoteObject> arguments,
String evalExpression, List<Object> arguments,
{bool returnByValue = false}) async {
var jsArguments = arguments.map(callArgumentFor).toList();
var result =
Expand Down Expand Up @@ -550,4 +556,23 @@ function($argsString) {
handleErrorIfPresent(extensionsResult, evalContents: expression);
return List.from(extensionsResult.result['result']['value'] as List);
}

/// Convert a JS exception description into a description containing
/// a Dart stack trace.
Future<String> mapExceptionStackTrace(String description) async {
RemoteObject mapperResult;
try {
mapperResult = await _jsCallFunction(
stackTraceMapperExpression, <Object>[description]);
} catch (_) {
return description;
}
var mappedStack = mapperResult?.value?.toString();
if (mappedStack == null || mappedStack.isEmpty) {
return description;
}
var message = exceptionMessageRegex.firstMatch(description)?.group(0);
message = (message != null) ? '$message\n' : '';
return '$message$mappedStack';
}
}
58 changes: 14 additions & 44 deletions dwds/lib/src/injected/client.js

Large diffs are not rendered by default.

10 changes: 7 additions & 3 deletions dwds/lib/src/services/chrome_proxy_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -842,15 +842,19 @@ ${globalLoadStrategy.loadModuleSnippet}("dart_sdk").developer.invokeExtension(
..timestamp = e.timestamp.toInt());
});
if (includeExceptions) {
exceptionsSubscription = remoteDebugger.onExceptionThrown.listen((e) {
exceptionsSubscription =
remoteDebugger.onExceptionThrown.listen((e) async {
var isolate = _inspector?.isolate;
if (isolate == null) return;
var description = e.exceptionDetails.exception.description;
if (description != null) {
description = await _inspector.mapExceptionStackTrace(description);
}
controller.add(Event(
kind: EventKind.kWriteEvent,
timestamp: DateTime.now().millisecondsSinceEpoch,
isolate: _inspector.isolateRef)
..bytes = base64.encode(
utf8.encode(e.exceptionDetails.exception.description ?? '')));
..bytes = base64.encode(utf8.encode(description ?? '')));
});
}
});
Expand Down
14 changes: 14 additions & 0 deletions dwds/test/chrome_proxy_service_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,8 @@ void main() {
var event = await stream
.firstWhere((event) => event.kind == EventKind.kPauseException);
expect(event.exception, isNotNull);
// Check that the exception stack trace has been mapped to Dart source files.
expect(event.exception.valueAsString, contains('main.dart'));

var stack = await service.getStack(isolateId);
expect(stack, isNotNull);
Expand Down Expand Up @@ -1660,6 +1662,18 @@ void main() {
await tabConnection.runtime.evaluate('console.error("Error");');
});

test('exception stack trace mapper', () async {
expect(service.streamListen('Stderr'), completion(_isSuccess));
var stderrStream = service.onEvent('Stderr');
expect(
stderrStream,
emitsThrough(predicate((Event event) =>
event.kind == EventKind.kWriteEvent &&
String.fromCharCodes(base64.decode(event.bytes))
.contains('main.dart'))));
await tabConnection.runtime.evaluate('throwUncaughtException();');
});

test('VM', () async {
var status = await service.streamListen('VM');
expect(status, _isSuccess);
Expand Down
4 changes: 4 additions & 0 deletions fixtures/_test/example/hello_world/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ void main() async {
log(message, name: 'testLogCategory');
};

context['throwUncaughtException'] = () {
scheduleMicrotask(() => throw Exception('UncaughtException'));
};

Timer.periodic(const Duration(seconds: 1), (_) {
printCount(); // Breakpoint: callPrintCount
});
Expand Down
4 changes: 4 additions & 0 deletions fixtures/_testSound/example/hello_world/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ void main() async {
log(message, name: 'testLogCategory');
};

context['throwUncaughtException'] = () {
scheduleMicrotask(() => throw Exception('UncaughtException'));
};

Timer.periodic(const Duration(seconds: 1), (_) {
printCount(); // Breakpoint: callPrintCount
});
Expand Down