I'm currently dealing with a library that is throwing errors:
throw new Error('The connection timed out waiting for a response')
This library has the potential to throw errors for various reasons, making it challenging for users to handle the errors programmatically in different ways without resorting to switch
statements based on error.message
, which I find less than ideal since the message isn't really designed for programmatic decision-making purposes. Many people tend to subclass the Error
, but I feel like that might be going overboard. Instead, I'm contemplating either (a) overriding error.name
with a custom name:
const error = new Error('The connection timed out waiting for a response');
error.name = 'ConnectionTimeout';
throw error;
or (b) setting a non-standard property such as error.code
:
const error = new Error('The connection timed out waiting for a response');
error.code = 'ConnectionTimeout';
throw error;
Is there a recommended approach among these options? Are there any concerns or criticisms associated with either of these approaches? I came across a discussion related to this topic, but it appears inconclusive and potentially outdated in terms of current conventions: