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)