DEV Community

Discussion on: Error Handling in JavaScript (Golang Style)

Collapse
 
jsnanigans profile image
Brendan Mullins

Nice, but I would personally use an object instead of the array as a return type

Collapse
 
bibekkakati profile image
Bibek

I prefer array because if we use object, destructuring will be an issue if there is more than one block in same level. Also we need to be aware of the property name.

Collapse
 
jankapunkt profile image
Jan Küster

Property name can be set by convention across your whole project. Let's say { error, result } which is to me most verbose and would not lead to accidental access compared to array indices

Thread Thread
 
bibekkakati profile image
Bibek

Yeah, that is right. But in case of multiple blocks in the same scope it can create issue, as you will not be able de-structure it like this

const {error, result} = await method();

// second method call will create an issue
const {error, result} = await method2();
Enter fullscreen mode Exit fullscreen mode

But in case of array, you can use other variable name in the second method call.

Feel free to correct me, if I am missing something.

Thread Thread
 
jsnanigans profile image
Brendan Mullins

a few ways you could avoid this:

const responseOne = await methodOne();
if (responseOne.error) return

const responseTwo = await methodTwo();
if (responseTwo.error) return

// of if you want destructuring
const {error: methodOneError, result: resultOne} = await methodOne();
if (methodOneError) return
const {error: methodTwoError, result: restultTwo} = await methodTwo();
if (methodTwoError) return
Enter fullscreen mode Exit fullscreen mode

Im not saying the array descructuring is worse, its just a prefference

Thread Thread
 
erikhofer profile image
Erik Hofer

You can rename the variable when destructuring an object.

const {error, result} = await method();

const {error: error2, result: result2} = await method2();
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
bibekkakati profile image
Bibek

@jsnanigans Yeah, It's just a preference.

Thread Thread
 
bibekkakati profile image
Bibek • Edited

@erikhofer I am aware of that.