Search code examples
javascriptcoding-style

What's the best best practice to validate object fields?


The below function has to validate the the required object fields before proceeding further. There is no strict requirement to return a generic validation error messages versus specific error message. What's the best practice to be followed?

Returning generic validation message,

function getAccountDetails({userId, accountId, email}) {
 if(!userId || !accountId || !email) {
   return 'userId or accountId or email is required';
 }
 // Todo

}

Returning specific validation error message,

 function getAccountDetails({userId, accountId, email}) {
  if(!userId) {
    return 'userId is required';
  }
  if(!accountId) {
    return 'accountId is required';
  }
  if(!email) {
    return 'email is required';
  }
  // Todo

}

Solution

  • I would say none of them is best. as the function is expected to return the account details not the errors.

    A good practice will be to throw the error and catch it on the other side using try/catch block.

    if(!userId || !accountId || !email) {
       throw Error("userId or accountId or email is required")
     }
    

    between from both of the approaches ... do what suits you best or you think is best there is no any recommendation.