Sdk: Add function to rethrow with a provided stacktrace.

Created on 15 Sep 2017  路  6Comments  路  Source: dart-lang/sdk

Add a static rethrow method (with a different name since rethrow is reserved) that can synchronously throw an object and a stack trace. Currently there is no way to reuse an existing stack trace when throwing synchronously in a sync function, but you can do await new Future.error(object, stackTrace) in an async function. It's occasionally useful, and we have the functionality anyway (_rethrow in dart:async/zone.dart), so we should allow it in sync functions too.

Maybe as a static on Error: void Error.throwWithStack(Object error, [StackTrace stackTrace]); (maybe no need to make the stack trace optional, but it can then get the stackTrace from error if it implements Error).

area-library core-l library-core type-enhancement

Most helpful comment

It would also be cool to have rethrow foo to mean "throw foo with the same stack trace that would be used with rethrow;".

All 6 comments

it seems like this would also address https://github.com/dart-lang/sdk/issues/10297

+1 I ran into a situation where I needed to do this.

throw foo at bar;

It would also be cool to have rethrow foo to mean "throw foo with the same stack trace that would be used with rethrow;".

Being able to throw or rethrow an exception at a particular stack trace (i.e. to preserve the original stacktrace) would be very valuable for something like https://github.com/flutter/flutter/pull/34626.

I need this to improve error handling for the AsyncRedux package. I currently have this code, which may loose the StackTrace.

    } catch (error) {
      dynamic processedError = _processError(error, action, afterWasRun);

      // Error is meant to be "swallowed".
      if (processedError == null)
        return;

      // Error was not changed. Rethrows.
      else if (identical(processedError, error))
        rethrow;

      // Error was changed. Rethrows, but looses stacktrace due to Dart architecture.
      // See: https://groups.google.com/a/dartlang.org/forum/#!topic/misc/O1OKnYTUcoo
      // See: https://github.com/dart-lang/sdk/issues/10297
      // This should be improved when this issue is solved: https://github.com/dart-lang/sdk/issues/30741
      else
        throw processedError;
    }
Was this page helpful?
0 / 5 - 0 ratings