eslint-plugin-ava icon indicating copy to clipboard operation
eslint-plugin-ava copied to clipboard

Rule proposal: `prefer-t-throws`

Open gajus opened this issue 9 years ago • 10 comments

Issuehunt badges

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)

Submitted pull Requests


Become a backer now!

Or submit a pull request to get the deposits!

Tips

gajus avatar Nov 13 '16 18:11 gajus

Sounds like a good idea to me :+1:. 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.

try {
  await request(requestOptions);
  t.fail();
} catch (error) {
  t.true(error.statusCode === 500);
}

jfmengels avatar Nov 13 '16 20:11 jfmengels

The second example is better, but FYI, using t.fail() would improve your first example.

Another idea for a lint rule. :-)

gajus avatar Nov 13 '16 20:11 gajus

👍 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?

sindresorhus avatar Nov 14 '16 03:11 sindresorhus

Agreed

jfmengels avatar Nov 14 '16 07:11 jfmengels

I think prefer-t-throws would be a better name. We don't want to prevent all usage of try/catch. Thoughts?

What would be a valid use case for try..catch that cannot translate to t.throws?

gajus avatar Nov 14 '16 09:11 gajus

I think that t.throws() handles every case you'd use a try catch for, and even the Promise#catch() case.

jfmengels avatar Nov 14 '16 11:11 jfmengels

@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 than no-try-catch; We want to recommend using t.throws(), not arbitrarily prevent try/catch.

sindresorhus avatar Nov 14 '16 14:11 sindresorhus

The immediate valid use case for try..catch that came up in my mind is error handling in Koa:

app.use(function * (next) {
  try {
    yield* next;
  } catch (err) {
    // handle error
  }  
});

vadimdemedes avatar Nov 14 '16 20:11 vadimdemedes

We don't want to prevent all usage of try/catch.

Definitely agree with this.

vadimdemedes avatar Nov 14 '16 20:11 vadimdemedes

@issuehunt has funded $80.00 to this issue.


IssueHuntBot avatar Apr 11 '19 04:04 IssueHuntBot