unhurried

コンピュータ関連ネタがほとんど、ときどき趣味も…

Error Handling in JavaScript

When we handle exceptions in Java, it is common to declare classes which extend Exception class and make conditional branches with instanceof operator. As far as I researched about how to do in JavaScript, there are mainly two ways.

  1. Extend Error object
    • Declare classes which extend Error object (For before ES5: prototype of Error object) and make conditional branches with instanceof operator.
    • Using instanceof operator makes the comparison reliable, but Error classes have to be imported in the file where conditional branches exist.
  2. Change the name property of Error object.
    • Create an Error object and change the name property, then make conditional branches by strings set as the name property.
    • This method is simple, but thereis a possibility that the names of the errors may be the same as the ones defined in the dependent modules.

Sample Code

error.js

var ERROR = {};

// As the original value of the name priperty of Error object is "Error",
// change it to a name of the custom Error class.
ERROR.Error1 = class extends Error {}
ERROR.Error1.prototype.name = "Error1";

// For before ES5, implement the inheritance using prototype.
ERROR.Error2 = function (message) {
    this.message = message;
}
ERROR.Error2.prototype = new Error;
ERROR.Error2.prototype.name = "Error2";

module.exports = ERROR;

module.js

const ERROR = require('./error.js');

class MyClass {
    static myMethod(arg) {
        if (arg === 1) {
            throw new ERROR.Error1("Error1 occured.")
        } else if (arg === 2) { 
            throw new ERROR.Error2("Error2 occured.")
        } else if (arg === 3) { 
            const e = new Error("Error3 occured.")
            e.name = "Error3";
            throw e;
        }
    }
}

module.exports = MyClass;

main.js

const MyClass = require('./module.js');
const ERROR = require('./error.js');

try {
    MyClass.myMethod(1);
} catch(e) {
    if (e instanceof ERROR.Error1) {
        console.log(e.name);
        console.log(e.message);
    }
}

try {
    MyClass.myMethod(2);
} catch(e) {
    if (e instanceof ERROR.Error2) {
        console.log(e.name);
        console.log(e.message);
    }
}

try {
    MyClass.myMethod(3);
} catch(e) {
    if (e.name === "Error3") {
        console.log(e.name);
        console.log(e.message);
    }
}

Result

$ node main.js
Error1
Error1 occured.
Error2
Error2 occured.
Error3
Error3 occured.

Reference