Vue3/State management/Components: Unnecessary Try/Catch

Viewed 24

I hope there is a general consensus to this question and I'm not asking for people's opinions.

My component dispatches a action method:

await dispatch('someAction', payload)

Store

async someAction({commit}, payload){
  try {
    const data = await http.get('/foobar', payload)
    commit('someCommit', data.data)
  } catch (error) {
    throw error
  }
}

In the store method, the try/catch is throwing an Eslint error unnecessary try/catch, which to me doesn't make sense. The server can throw an error and the http call can fail, so in order to avoid the commit from firing I added a try/catch block. I guess I could add a if (data) commit(... but isn't it cleaner with a try/catch?

Also, in the catch I'm throwing the error so that the original dispatch call can be stopped (if it was in its own try/catch).

Am I doing things wrong here? Is there a 'better' way of doing things?

1 Answers

From the docs

A catch clause that only rethrows the original error is redundant, and has no effect on the runtime behavior of the program. These redundant clauses can be a source of confusion and code bloat, so it’s better to disallow these unnecessary catch clauses.

The preferred way to handle an error is to... well, handle it. Log it, respond to it in some way, just don't throw it. However, as the docs also say,

If you don’t want to be notified about unnecessary catch clauses, you can safely disable this rule.

Which can be done in your eslint config:

"rules": {
  "no-useless-catch": "off" // "off" or 0 both work
}
Related