Day 12 — Errors and modules

Hands-on

Topic 1 Part 1
function safeParse(str) {
    try {
        const data = JSON.parse(str);
        return data
    }
    catch (err){
        console.log("invalid JSON :", err.message);   
        return null;
    }
}

Try the steps, then compare with ../js/hands-on.js (loaded at the bottom of this page).

Section 2 Part 2
console.log(safeParse('{"name":"Priya"}'));
console.log(safeParse('{"name":"Priy'));

Try the steps, then compare with ../js/hands-on.js (loaded at the bottom of this page).

Section 3 Part 3
function setAge(age) {
    if(typeof age != "number") 
        throw "age must be a number"
    if(age > 120) 
        throw "age must be 0–120"
    else 
        return age;
}

Try the steps, then compare with ../js/hands-on.js (loaded at the bottom of this page).

Section 4 Part 4
try {
    console.log(setAge(20));
    console.log(setAge("twenty"));
    console.log(setAge(200));
}
catch(err) {
    console.log(err);
} finally {
    console.log("shock ayyara")
}

Try the steps, then compare with ../js/hands-on.js (loaded at the bottom of this page).

Section 5 Part 5
class ValidationError extends Error {
    constructor(message) {
        super(message)
        this.name = "Validation Error"
    }
}

Try the steps, then compare with ../js/hands-on.js (loaded at the bottom of this page).

Section 6 Part 6
function validateEmail(email) {
    if(!email.includes('@')) {
        throw new ValidationError("invalid email error");
    }
    return "valid email"
}

Try the steps, then compare with ../js/hands-on.js (loaded at the bottom of this page).

Section 7 Part 7
try {
    console.log(validateEmail("kalyan@.gmas"));
    console.log(validateEmail("kalyan.gmas"));

Try the steps, then compare with ../js/hands-on.js (loaded at the bottom of this page).

Section 8 Part 8
} catch(err) {
    if(err instanceof ValidationError) {
        console.log("validation failed",err.message)
    }
}

Try the steps, then compare with ../js/hands-on.js (loaded at the bottom of this page).