GOXR3PLUS
GOXR3PLUS

Reputation: 7255

Try Catch Not working with Promise and Redux Thunk

Feel free to edit the title as i didn't knew how to properly express .

We are using React 6.13,Babel 7,Node 12


Well , i am trying to refactor our thousands lines of code and one of the things i have to do for the duplicate code is create a try-catch-wrapper function because we are doing the same for every error .

So below is the wrapper function :

const tryToCatch = (func, data ,dispatch) => {
   try {
      func()
      console.log('mmmm')
   } catch (error) {
      console.log('Error: ', error)
      console.log(data)
      return handleError(error, data , dispatch)
   }
}

And below is how i am trying to call it , i am using console.log(a) which prints:

enter image description here

BUT IT SEEMS LIKE IT'S NEVER ENTERS CATCH because console.log('Error: ', error) and console.log(data) are never printed .

export const search = () => async dispatch =>
   tryToCatch(
      async () => {

         //Get Games
         const { data } = await serverApi('GET', '/api/common/games')

         console.log(a) //a is undefined so it will try to catch error

         console.log("hello");

         ..etc code
      },
      dispatch,
      { filtersLoading: false }
   )

Upvotes: 0

Views: 1031

Answers (2)

MonteCristo
MonteCristo

Reputation: 1550

const tryToCatch = async (func, data ,dispatch) => { // Missing `async`
   try {
      await func()
      console.log('mmmm')
   } catch (error) {
      console.log('Error: ', error)
      console.log(data)
      return handleError(error, data , dispatch)
   }
}

Upvotes: 1

Kunal Gupta
Kunal Gupta

Reputation: 86

The callback function is async, try-catch only works synchronously. You can make tryToCatch an async function and add await before the func() call.

const tryToCatch = async (func, data ,dispatch) => {
   try {
      await func()
      console.log('mmmm')
   } catch (error) {
      console.log('Error: ', error)
      console.log(data)
      return handleError(error, data , dispatch)
   }
}

Reference: https://javascript.info/try-catch

Upvotes: 1

Related Questions