Coding / Programming Videos

Post your favorite coding videos and share them with others!

Is there a best practice way to handle errors? : javascript

Source link

I was looking at this eslint rule (https://eslint.org/docs/rules/no-throw-literal) that gave me a linting error and I was wondering if it’s still valid. It says that the reason why you should only throw instances of Error is because Error keeps information about where the Error was thrown. Is this still true? I noticed when I throw an object, for example like this:

// option 1
throw { statusCode: 400, message: 'req.body.name needs to be a string' }

It will show information about what line number the throw was. It’s also nice because I get to access extra information about the error, like what type of error statusCode I should send back.Is this eslint rule still valid and if it is, is there a best practice way to pass information? I thought of a few ways to do this and I’m wondering which way would be the best, here are some ways:

// option 2
const error = new Error('req.body.name needs to be a string')
error.statusCode = 400
throw error

I’m not sure if there are some downsides to doing it the option 2 way. Here’s another way:

// option 3
throw new Error(
  JSON.stringify({
    statusCode: 400,
    message: 'req.body.name needs to be a string'
  })
)

I’m not sure if option 3 would work because I would have to do some weirdness to get the contents of error.message. Another way would be just not throwing errors and instead having a standard way of returning error objects and checking if they’re an error type or a success type:

// option 4
return {
  type: 'ERROR',
  error: { statusCode: 400, message: 'req.body.name needs to be a string' }
}

I actually kind of like option 4 because the type of error could be reflected in the types if I’m using TypeScript or Flow, which would help prevent runtime errors and increase understandability of what types of errors a function can return, which might help with debugging. But I guess option 4 might be too verbose because I would have to use an if-statement for every function that can return an error and check if that error exists or if it’s successful.

Is there a best practice way to handle errors in JavaScript?

Source link

Bookmark(0)
 

Leave a Reply

Please Login to comment
  Subscribe  
Notify of
Translate ยป