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:
Custom Error: In JavaScript, we create a custom error by extending the built-in
Error
class. OurArgError
class takesarg
andmessage
as parameters and constructs an error message.Error Throwing: Instead of returning errors, in JavaScript we throw them using the
throw
keyword.Error Handling: We use try-catch blocks to handle errors in JavaScript. The
catch
block receives the thrown error as a parameter.Type Checking: To check if an error is of a specific type, we use the
instanceof
operator. This is similar to Go’serrors.As()
function, allowing us to identify and handle specific error types.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.