Custom Errors in TypeScript
Custom errors can be implemented in TypeScript by extending the built-in Error
class. Here’s an example that demonstrates this concept:
import { format } from 'util';
// A custom error type usually has the suffix "Error".
class ArgError extends Error {
constructor(public arg: number, message: string) {
super(message);
this.name = 'ArgError';
}
toString(): string {
return format('%d - %s', this.arg, this.message);
}
}
function f(arg: number): number {
if (arg === 42) {
// Return our custom error.
throw new ArgError(arg, "can't work with it");
}
return arg + 3;
}
function main() {
try {
f(42);
} catch (err) {
// TypeScript doesn't have a direct equivalent to Go's errors.As,
// but we can use instanceof to check the error type.
if (err instanceof ArgError) {
console.log(err.arg);
console.log(err.message);
} else {
console.log("err doesn't match ArgError");
}
}
}
main();
In this TypeScript version:
We define a custom
ArgError
class that extends the built-inError
class. This is similar to implementing theerror
interface in Go.The
ArgError
class has a constructor that takes anarg
and amessage
. It also overrides thetoString
method to provide a custom string representation of the error.The
f
function throws anArgError
when the argument is 42, similar to returning a custom error in Go.In the
main
function, we use a try-catch block to handle the error. This is different from Go’s approach of returning errors, but it’s the idiomatic way to handle errors in TypeScript.Instead of
errors.As
, we use theinstanceof
operator to check if the caught error is an instance ofArgError
. This allows us to access the specific properties of our custom error.
To run this TypeScript program:
$ ts-node custom-errors.ts
42
can't work with it
Note that you’ll need to have TypeScript and ts-node installed to run this directly. Alternatively, you can compile it to JavaScript and run it with Node.js.
This example demonstrates how to create and use custom errors in TypeScript, providing similar functionality to Go’s custom errors.