Custom Errors in JavaScript

// A custom error type usually has the suffix "Error".
class ArgError extends Error {
    constructor(arg, message) {
        super(`${arg} - ${message}`);
        this.name = "ArgError";
        this.arg = arg;
        this.message = message;
    }
}

function f(arg) {
    if (arg === 42) {
        // Return our custom error.
        throw new ArgError(arg, "can't work with it");
    }
    return arg + 3;
}

function main() {
    // In JavaScript, we use try-catch for error handling
    try {
        f(42);
    } catch (err) {
        // In JavaScript, we check the instance of the error
        if (err instanceof ArgError) {
            console.log(err.arg);
            console.log(err.message);
        } else {
            console.log("err doesn't match ArgError");
        }
    }
}

main();

In JavaScript, we don’t have a direct equivalent to Go’s errors.As() function. Instead, we use the instanceof operator to check if an error is of a specific type. Here’s an explanation of the key differences and concepts:

  1. Custom Error: In JavaScript, we create a custom error by extending the built-in Error class. Our ArgError class takes arg and message as parameters and constructs an error message.

  2. Error Throwing: Instead of returning errors, in JavaScript we throw them using the throw keyword.

  3. Error Handling: We use try-catch blocks to handle errors in JavaScript. The catch block receives the thrown error as a parameter.

  4. Type Checking: To check if an error is of a specific type, we use the instanceof operator. This is similar to Go’s errors.As() function, allowing us to identify and handle specific error types.

  5. Main Function: JavaScript doesn’t require a main function, but we’ve included one to keep the structure similar to the original example.

When you run this code, it will output:

42
can't work with it

This example demonstrates how to create and use custom errors in JavaScript, providing a way to handle specific error conditions with additional context.