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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay