Javascript: Custom exceptions

In Javascript custom exception can be created and make them caught by `catch`.
For example lets see below code

let json = '{ "age": 30 }'; // incomplete data
try {
  let user = JSON.parse(json);  
  if (!user.name) {
    throw new Error("Incomplete data: no name"); 
  }
  alert( user.name );
} catch (err) {
  alert( "JSON Error: " + err.message ); // JSON Error: Incomplete data: no name
}
Hope it helps.
Thank you.

Comments

Popular posts from this blog

grep: unknown device method

Uploading files to FTP/SFTP using CURL

How to find outgoing IP in Linux ?