DEV Community

Mišo
Mišo

Posted on

Correct exception names in Javascript

If you have your own exception hierarchy in the app you probably noticed your perfectly named exceptions show like this in the console or Sentry: Error: something happened and I don't like it. The Error prefix is the name of the exception. I would expect something like this MalformedData: I like different data more. Got: "bad data".

The trick is to set a name attribute of the Error. People do it in every exception in constructor like this.

export class AppException extends Error {}

export class ResourceNotFound extends AppException {
  constructor(
    public resource: string,
    public id: unknown,
  ) {
    super(`The resource '${resource}' with id ${id} is not found.`);
    this.name = 'ResourceNotFound';
  }
}

export class MalformedData extends AppException {
  constructor(data: unknown) {
    super(`I like different data more. Got: ${JSON.stringify(data)}`);
    this.name = 'MalformedData';
  }
}
Enter fullscreen mode Exit fullscreen mode

It is very repetitive and you can forget to do it easily. Also, if you don't need a special constructor for your exception it adds some boiler plate. It can be shortened by setting the name directly:

export class ResourceNotFound extends AppException {
  override readonly name = 'ResourceNotFound';
}
Enter fullscreen mode Exit fullscreen mode

But the ultimate solution for me is to set it once in the top-level exception and let it be derived automatically. Setting it to readonly prevents people overwriting it too.

export class AppException extends Error {
  override readonly name = this.constructor.name;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!