rspec/rules/S1679/dart/rule.adoc

52 lines
1.2 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
In dart `throw` is used no initiate an exception. Usually this is enough to just catch it and handle. However, there are cases when the exceptions needs to be propagated further after being caught. This allows a handling of the exception on different levels.
In such case it's recommended to use `rethrow` instead of just `throw`, to preserve the original stacktrace.
[source,dart]
----
try {
...
} catch (ex, stacktrace) {
rethrow ex; // preserves the original exception with its stacktrace
}
----
== How to fix it
The rule raises an issue when the argument of the `throw` expression is an unmodified copy of the caught exception.
=== Code examples
==== Noncompliant code example
[source,dart,diff-id=1,diff-type=noncompliant]
----
void foo() {
try {
methodThrowsException();
} catch (ex) {
// ...
throw ex; // Noncompliant
}
}
----
==== Compliant solution
[source,dart,diff-id=1,diff-type=compliant]
----
void foo() {
try {
methodThrowsException();
} catch (ex) {
// ...
rethrow ex;
}
}
----
== Resources
* https://dart.dev/tools/linter-rules/use_rethrow_when_possible[Dart Lint rule]