Open
Description
I was reviewing some codes using ava and found this pattern repeating often:
try {
await request(requestOptions);
} catch (error) {
t.true(error.statusCode === 500);
}
This can be written instead as:
const error = await t.throws(request(requestOptions));
t.true(error.statusCode === 500);
I think the latter should be preferred.
IssueHunt Summary
Backers (Total: $80.00)
issuehunt ($80.00)
Submitted pull Requests
Become a backer now!
Or submit a pull request to get the deposits!
Tips
- Checkout the Issuehunt explorer to discover more funded issues.
- Need some help from other developers? Add your repositories on IssueHunt to raise funds.
Activity
jfmengels commentedon Nov 13, 2016
Sounds like a good idea to me 👍. Not sure when/why try/catch makes sense in tests when t.throws is available.
The second example is better, but FYI, using
t.fail()
would improve your first example.gajus commentedon Nov 13, 2016
Another idea for a lint rule. :-)
[-]rule proposal: no try-catch[/-][+]Rule proposal: `no-try-catch`[/+]sindresorhus commentedon Nov 14, 2016
👍 Sounds good. PR welcome :)
I think
prefer-t-throws
would be a better name. We don't want to prevent all usage of try/catch. Thoughts?jfmengels commentedon Nov 14, 2016
Agreed
[-]Rule proposal: `no-try-catch`[/-][+]Rule proposal: `prefer-t-throws`[/+]gajus commentedon Nov 14, 2016
What would be a valid use case for
try..catch
that cannot translate tot.throws
?jfmengels commentedon Nov 14, 2016
I think that
t.throws()
handles every case you'd use a try catch for, and even thePromise#catch()
case.sindresorhus commentedon Nov 14, 2016
@gajus Maybe something that might throw, but that you don't care about in the test, so you'd like to silence it. I'm sure there are other cases we can't think of too. But the main point is that the intent is clearer with
prefer-t-throws
thanno-try-catch
; We want to recommend usingt.throws()
, not arbitrarily prevent try/catch.vadimdemedes commentedon Nov 14, 2016
The immediate valid use case for
try..catch
that came up in my mind is error handling in Koa:vadimdemedes commentedon Nov 14, 2016
Definitely agree with this.
5 remaining items