What is the most effective method for displaying an error code when a JavaScript error occurs?

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:

Answer №1

This is an enhanced excerpt from a larger answer I have written, focusing on error messages for better clarity.

Clear Error Messages Matter

Let's consider common code like this:

function add( x, y ) {
  if(typeof x !== 'number')
    throw new Error(x + ' is not a number')
  
  if(typeof y !== 'number')
    throw new Error(y + ' is not a number')
  
  return x + y
}

Each time the function is called with a different non-numeric value for x, the resulting error message varies:

add('a', 1)
//> 'a is not a number'

add({ species: 'dog', name: 'Fido' }, 1) 
//> '[object Object] is not a number'

The issue here is that each error message differs, making it harder to handle errors at runtime effectively. It even becomes unclear which variable (x or y) is causing the problem.

To address this, it's recommended to use consistent static strings for error messages in your code and establish clear conventions for yourself.

When it comes to objectionable values, make sure your error messages follow a specific format for easy identification and handling:

objection + space + topic
// e.g.
"unknown planetName"

There are standard objections like missing, unknown, unavailable, etc., alongside the specific datapoint causing the issue.

For failed operations, simply include the operation name followed by "failed". Keep error messages concise and focused on conveying the necessary information without extra prose.

Remember, it's crucial to be honest in constructing your error messages to avoid misleading information when debugging.

Choosing the Right Error Type

Stick to throwing instances of Error or its sub-classes for consistency and compatibility with existing browser and third-party codebases. Ensure error messages are precise and informative to aid in efficient error handling.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

If the first <select> option is chosen, then a second <select> validation is necessary

Is it possible to make the second selection required for validation only if the 'yes' option is selected in the first one? <div class="form-group" ng-class="{ 'has-error' : articleEditForm.pnp.$invalid && !articleEditForm.pn ...

Contains a D3 (version 3.4) edge bundle chart along with a convenient update button for loading fresh datasets

I am looking to update my D3 (v3.4) edge bundling chart with a new dataset when a user clicks an 'update' button. Specifically, I want the chart to display data from the data2.json file instead of data1.json. Although I have started creating an u ...

Conflict between Angular's ng-repeat directive and Sass styling

Currently, I am working on a project and encountering an issue that is causing some difficulty: In order to create a navigation bar with equally distributed list elements based on the number of items, I am utilizing ng-repeat for data binding and Sass for ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Why isn't this working? I'm attempting to trigger a sound when I hover with my cursor, but it only plays when I click instead

When I click on it, it works fine. But I can't seem to get it to work on hover. Can someone help me out? This is the HTML code: <body> <audio autoplay id="HAT2" > <source src="OOOOO_1_HAT.mp3" > Your browser doesn't support t ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

When using a master page in ASP.Net webforms, the autocomplete feature may not function correctly

I'm encountering an issue with a script on my website. I have a web form called CoursesPage.aspx that utilizes a master page. I have implemented autocomplete functionality using jQuery on a textbox to display course names fetched from a database. The ...

SVG tags are not functioning properly

Hello, I am new to working with SVG files. I have a set of icons created using SVG and I am attempting to use the <use> tag in order to display a specific part of an SVG file. However, I seem to be encountering some issues and I am unable to identi ...

AngularJS Uncaught ReferenceError: variable is not

I am facing an issue where I cannot retrieve a value from a function. I am performing REST requests for testing purposes and when trying to get a date, it always returns undefined. An Illustration $http.get('app/components/home/controller/test_calen ...

Optimizing express server dependencies for a smooth production environment

After developing an application with a React front end and a Node server on the backend, I found myself wondering how to ensure that all dependencies for the server are properly installed when deploying it on a container or a virtual machine. Running npm ...

Is it necessary to bump the major version if I make updates to a react module that does not affect existing code functionality, but may cause Jest snapshot tests to break?

Imagine I am developing a module for a react component and currently working on a PR to introduce a new feature. Along with this new feature, I have also made changes to the component by refactoring it to eliminate certain internal parts that were previou ...

When I click a button in d3 to refresh the data on my bar graph, the text fails to update accordingly

I've successfully created a series of data lists that modify the bargraph. Unfortunately, due to their differing x and y values, they end up printing new values on top of existing ones. Shown below is an image illustrating the issue where x and y val ...

Database-driven cron scheduling

How can I set up a cron job to send an email notification using node-mailer about 1 or 2 weeks before the expiration date of a product in my database that includes an expired_date field? ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

Steps for installing a package using npm without the need for configuring a package.json file

According to this source, it is feasible to install npm packages before creating the package.json file. After installing nodeJS on my computer, I attempted to run the following command in an empty directory: npm install jQuery This resulted in the follow ...

Methods for displaying data on the client side using express, MongoDB, and jade

I'm currently working on displaying data retrieved from my database using node.js, Express, and MongoDB. I successfully see the data in the console, but now I need to output it on the front-end using Jade. Here is the data I have retrieved: { date: ...

Increase the progress bar at regular intervals of x seconds

I am looking for a jQuery UI progress bar that will increase by x amount every x seconds. Once it reaches 100%, I need it to trigger a function to retrieve some content. Essentially, I need a timer-like feature. EDIT: Note that I do not require any code ...

I have successfully converted an SQL Join query into JSON, but now I am unsure of how to interact with the

I recently ran an SQL Join on two tables and obtained the following results: _____People_____ name: "Jane" age: 35 job_id: 1 _____Professions_____ job_id: 1 title: "Teacher" "SELECT * FROM People INNER JOIN Professions ON People.job_id = Professions.job ...

What is the best way to ensure consistency in a value across various browsers using Javascript?

I am currently developing a feature on a webpage that displays the last update date of the page. The functionality I am aiming for is to select a date in the first input box, click the update button, and have the second box populate the Last Updated field ...

Guide on How to Show Only the Initial Word of an H2 Header Using JavaScript or CSS

Is there a way to display only the first word from an h2 heading? For instance: In the website's source code, it would appear like this <h2> Stackoverflow is an Ideal Place</h2> But on the live website, it should be displayed like this ...