try {const uri = decodeURI('http%test');// We never get hereconsole.log('Success!');}catch (error) {console.log(error);}finally {console.log('The operation (and any error handling) is complete');}
Catching Different Types of Errors
try {// Some code that will raise an error}catch (error) {if (error instanceof RangeError) {// Do something about the value being out of range}else if (error instanceof TypeError) {// Do something about the value being the wrong type}else {// Rethrow the errorthrow error;}}
Catching Asynchronous Errors
const request = new XMLHttpRequest();request.onerror = function errorHander(error) {console.log(error);}request.open('GET', 'http://noserver');request.send();fetch('http://noserver').then((response) => {console.log('We did it, fam.');}).catch((error) => {console.log(error);});
Detecting Unhandled Errors
// Attach the event handlerwindow.onerror = (message, url, lineNo, columnNo, error) => {console.log(`An unhandled error occurred in ${url}`);}// Cause an unhandled errorconsole.log(null.length);// Attach the event handlerwindow.onunhandledrejection = (e) => {console.log(e.reason);}// Create a promise that will cause an unhandled asynchronous errorconst faultyPromise = new Promise(() => {throw new Error('Disaster strikes!');});// Create a promise that rejects (also triggers window.onunhandledrejection)const rejectedPromise = new Promise((resolve, reject) => {reject(new Error('Another disaster strikes!'));});window.onunhandledrejection = (e) => {console.log('An error occurred, but we won\'t tell you what it was');// Cancel the default error handlinge.preventDefault();}