joelanman,
@joelanman@hachyderm.io avatar

This feels a bit wonky to me. You can't use const like this:

try {  
 const myVar = myFunc(options)  
} catch (error) {   
 console.error(error)  
}

console.log(myVar)  

as myVar doesn't exist outside the try scope. So if you need to do a try catch, you have to use let - even if you actually want to use the variable as a const (not change it later)

let myVar  
try {  
 myVar = myFunc(options)  
} catch (error) {   
 console.error(error)  
}

console.log(myVar)  

#javaScript

joelanman,
@joelanman@hachyderm.io avatar

this looks pretty smart, not sure I fully understand it though

https://stackoverflow.com/a/49664174

@woodsbythesea

woodsbythesea,
@woodsbythesea@fosstodon.org avatar

@joelanman Can you not wrap your try/catch in a function and return myFunc instead so you don't need a variable?

joelanman,
@joelanman@hachyderm.io avatar

@woodsbythesea sorry not sure I follow can you give an example?

woodsbythesea,
@woodsbythesea@fosstodon.org avatar

@joelanman It really depends what myFunc is doing but here's a contrived example that fetches some data and displays it without requiring that additional variable. https://jsfiddle.net/vupmokc9/2/

joelanman,
@joelanman@hachyderm.io avatar

@woodsbythesea thanks! Yeh I shouldve given more context, I'm writing a controller in express.js, and in it I have to await a bunch of db calls. So without error handling I'd have

const users = await User.getUsers()  

but the db call can fail so I have to wrap with try. Claude.ai is suggesting wrapping all the code in the controller in the try, which sidesteps my const issue

woodsbythesea,
@woodsbythesea@fosstodon.org avatar

@joelanman Maybe still separate out the API layer and use Promise.all or Promise.allSettled? https://jsfiddle.net/wenyfudk/2/. It would still log the error but you'd get any resolved data back.

joelanman,
@joelanman@hachyderm.io avatar

@woodsbythesea in express you have to call next with the error, which exists at the controller level, so I don't think I can

  • All
  • Subscribed
  • Moderated
  • Favorites
  • javascript
  • DreamBathrooms
  • cubers
  • thenastyranch
  • InstantRegret
  • Youngstown
  • rosin
  • slotface
  • Durango
  • ngwrru68w68
  • khanakhh
  • kavyap
  • everett
  • mdbf
  • magazineikmin
  • JUstTest
  • cisconetworking
  • GTA5RPClips
  • osvaldo12
  • tacticalgear
  • ethstaker
  • modclub
  • tester
  • Leos
  • normalnudes
  • provamag3
  • megavids
  • anitta
  • lostlight
  • All magazines