DEV Community

Hammad Malik
Hammad Malik

Posted on • Edited on

Refactoring: Try-Catch for Variable Assignment in JS

I was refactoring an Express application when I came across a curious bit of code:

let email;

try {
  email = req.body.email;
} catch (err) {}

I believe this code is attempting to throw an error if the "name" property is missing in req.body – if req.body.name did not exist the assignment would cause an error and it would stop execution of the rest of the code.

However, that's not what happens! req.body.email is undefined, so it is perfectly possible to assign undefined as the value for the name variable.

I think hasOwnProperty is more reliable way to make sure req.body container an email:

if (!req.body.hasOwnProperty("name")) {
  const err = new ReferenceError("no name in request body.");
  throw err;
}

const {email} = req.body

PS: For Express specifically, I'm interested in learning more about validating the req.body using JSON Schema or Joi.

Top comments (1)

Collapse
 
rtpharry profile image
Matthew Harris • Edited

Those speech marks need escaping 😉