Sitemap

Error Handling In JavaScript(JS)

2 min readAug 24, 2024

--

Wondering how to handle error in in JavaScript. I am here to clear most of your confusion regarding error handling in JS using try catch.

Let work on error handling by taking an real life example.

Assume we are working on creating a API to register user. Then what are the steps to register user. First note down the step to register user.

  1. Receive new user data in backend api.
  2. After receiving the data check if there are all the compulsory field or not. If there are not all the compulsory field then throw error.
  3. After that check if the password match with confirm password or not.
  4. After that check if the given user email is already register or not.
  5. After all check and if there are no error, then only save user info in database and send success message.

Step: 1 & 2 Receive new user data and check if all the compulsory field are included or not.

const registerUser = (newUserData) => {
try {
const compulsoryField = [
{ id: "userName", name: "User Name" },
{ id: "email", name: "Email" },
{ id: "password", name: "Password" },
{ id: "confirmPassword", name: "Confirm Password" }
];
//validate required field
compulsoryField.forEach((field) => {
if (newUserData[field.id] === null || newUserData[field.id] === undefined) {
throw (`${field.name} is required field`)
}
})


console.log("User Register SuccessFully")
} catch (err) {
console.log(err);
}
}

const newUserData = { email: "rishi@gmail.com", password: "123456", confirmPassword: "123456" }
// const newUserData = {userName:"rishi", email:"rishi@gmail.com", password:"123456", confirmPassword:"123456"}

registerUser(newUserData);

The Above code log “User Name is required field”.

Get Rishikesh khakurel’s stories in your inbox

Join Medium for free to get updates from this writer.

And if we add userName like in commented newUserData then it will log “User Register Successfully”.

Step: 3 & 4 Now let’s validate password and confirmPassword match or not. And also validate if the user is already registed or not.

const registerUser = (newUserData) => {
try {
const compulsoryField = [
{ id: "userName", name: "User Name" },
{ id: "email", name: "Email" },
{ id: "password", name: "Password" },
{ id: "confirmPassword", name: "Confirm Password" }
];
//validate required field
compulsoryField.forEach((field) => {
if (newUserData[field.id] === null || newUserData[field.id] === undefined) {
throw ({status: 400, errorMessage:`${field.name} is required field`})
}
})
//validate if password match with confirmPassword or not
if(newUserData.password !== newUserData.confirmPassword){
throw ({status: 400, errorMessage:"Password doesn't match"})
}

//validate if user already exist or not
const registeredUserEmailList = ["rishi@gmail.com", "rejin@gmail.com", "diwash@gmail.com", "saurab@gmail.com", "kabin@gmail.com" ]

if(registeredUserEmailList.includes(newUserData.email)){
throw ({status: 409, errorMessage:`User exist with this email ${newUserData.email}. Login to continue`})
}

console.log({status: 200, successMessage:"User Register SuccessFully"})
} catch (err) {
console.log(err);
}
}

const newUserData = {userName:"rishi", email:"rishikesh@gmail.com", password:"12345", confirmPassword:"123456"}

registerUser(newUserData);

Now you all the validation is done. You can send this error in response.

--

--