JavaScript Error Handling

  1. Java script throw statement
throw 'Error2';   // String typethrow 42;         // Number typethrow true;       // Boolean typethrow {toString: function() { return "I'm an object!"; } };throw new Error('Problem!'); // throws object error
const err = new Error('Could not find the file');
console.log(Error.prototype.message)
Error class properties and method
the use of error class

Custom error class

class CustomException extends Error{
constructor(errorCode, customMessage) {
super(customMessage)
this.errorCode = errorCode;
this.customMessage = customMessage;
}
}
const customExcep = new CustomException("001", "field must be number");
CustomerException class properties and method
The use of CustomError class
  • try-catch-finally
Syntax of try-catch:try {«try_statements»} catch (error) {«catch_statements»}Syntax of try-finally:try {«try_statements»} finally {«finally_statements»}Syntax of try catch finally:try {«try_statements»} catch (error) {«catch_statements»} finally {«finally_statements»}
class CustomException extends Error{
constructor(errorCode, customMessage) {
super(customMessage)
this.errorCode = errorCode;
this.customMessage = customMessage;
}
}
try{
throw new CustomException("001", "field must be number");
}
catch(e){
if (e instanceof CustomException){
console.log(e.customMessage);
}
}finally{
console.log("finally always executed");
}
example of use CustomException class

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to add object fields conditionally in JavaScript

Binary Heap — MinHeap and Max Heap — In TypeScript and C#

Looking to the future of JavaScript

Prepack — The Latest Big Thing in JavaScript

A Hacker’s Introduction to WebAssembly

Golf Tournament Simulations

How to use Destructive Assignment

Send, Read and Delete SMS in React Native

Send, Read and Delete SMS in React Native

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
wahyu eko hadi saputro

wahyu eko hadi saputro

i am a reader

More from Medium

JavaScript , Git , NoSQL

Which JS Framework Your Project Requires: Angular vs. React 2022

More About JavaScript, Version Controlling, NoSQL

JavaScript — Object Oriented Programming: Prototype Property / Prototype Object / Prototype…