What is the best way to provide a JavaScript error code?

I have a library that throws errors:

throw new Error('The connection timed out waiting for a response')

It can cause errors for several different reasons, and it is difficult for users to program error handling in different ways without switching on error.message, which is less optimal, since the message is not really intended for making software decisions. I know many people of the subclass Error, but it seems to be overboard . Instead, I consider (a) overriding error.namewith a custom name:

const error = new Error('The connection timed out waiting for a response');
error.name = 'ConnectionTimeout';
throw error;

or (b) installation error.code(not a standard property):

const error = new Error('The connection timed out waiting for a response');
error.code = 'ConnectionTimeout';
throw error;

Is there a preferred approach? Have you frowned on any of these approaches? Here is the closest conversation I could find regarding the subject, but it seems unconvincing and possibly outdated with the new conventions: https://esdiscuss.org/topic/creating-your-own-errors

+4
source share

Source: https://habr.com/ru/post/1689429/


All Articles