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

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

Using JavaScript and jQuery to compare two JSON objects, then storing the result in a separate object

I am currently working on an API call that provides an updated JSON object, as well as a static JSON object file. My goal is to compare a specific value in the objects for teams with the same name. For example, if Team John had 22 members in the old file ...

Unable to fetch css file in Node.js

I am currently in the process of learning Node.js, but I have encountered a small issue with retrieving data from a css file. Interestingly, when I directly add the data to the index file's code, it seems to work perfectly. Let me share the relevant ...

I am interested in incorporating a captcha system using ajax

Recently, I implemented email and captcha validation in a form. Now, I am looking to make some modifications. Specifically, I want the form to not reload the page if the captcha is incorrect or left empty. This means that all fields that have already bee ...

What are the best practices for ensuring secure PUT and DELETE requests?

For the backend of my current project, I have a question regarding security measures. As an illustration, one of the tasks involves handling various "/notes" requests. /notes => retrieve all notes belonging to the authenticated user /notes => creat ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Creating images with LibCanvas

Currently, I am utilizing LibCanvas for canvas drawing on my HTML page. However, I am facing difficulty in drawing an image. Can someone provide assistance with this? UPDATE: The code snippet I am using is showing the image being drawn but then it disappe ...

Encountered an error: Uncaught TypeError - Unable to access property 'active' as it is undefined within React code

<script type="text/babel"> class Frame extends React.Component{ render(){ return ( <div> <h2 className="os-animation" dat ...

I am trying to access the serial number data from an array of objects in ReactJS. Can anyone guide me

Is there a way to extract data from an array of objects, such as getting the serial number in ReactJS? In my current code snippet, I have an array called "number" with values [1, 2, 3]. My goal is to retrieve and display these numbers as a string like th ...

The $route object in Vue is not configured

Currently, I am delving into the realm of Vue router and aiming to achieve programmatic navigation without relying on <router-link> in my templates file. Here is a glimpse of my router and view setup: router = new VueRouter({ routes: [ ...

When React object state remains unchanged, the page does not update automatically

i have a state object with checkboxes: const [checkboxarray_final, setCheckboxarray_final] = useState({ 2: ",4,,5,", 9: ",1,", }); i'm working on enabling check/uncheck functionality for multiple checkboxes: these are ...

Displaying the product quantity counter in the shopping cart immediately after adding the item

My website has a shopping cart quantity counter that doesn't update immediately when a product is added. Instead, it requires a page reload or navigation to another page for the change to be reflected. I would like the quantity counter to show the pro ...

Tips for showcasing varied information on Morris Chart

I am working with a Morris chart that is populated with a collection of data, each item containing 6 different data values. My goal is to switch between displaying two different sets of data. For example, I want to show the 'Target' data always ...

Locate all the properties that are empty within each object contained in a JavaScript array

Consider this scenario: if I were to have an array of JavaScript objects like the following: var jsObjects = [ {a: 1, b: 2, c: null, d: 3, e: null}, {a: 3, b: null, c: null, d: 5, e: null}, {a: null, b: 6, c: null, d: 3, e: null}, {a: null, ...

Tips for refreshing the Vuex store to accommodate a new message within a messageSet

I've been working on integrating vue-socket.io into a chat application. I managed to set up the socket for creating rooms, but now I'm facing the challenge of displaying messages between chats and updating the Vuex store to show messages as I swi ...

What is the method to identify the key responsible for triggering a textbox input event?

Suppose there is a textbox on the webpage: <input id='Sub' type='text'> To capture each time the input changes, you can use the following code: sub = document.getElementById('Sub'); sub.addEventListener('input&a ...

Maintain the value of `this` using a recursive setImmediate() function

Hey there! I'm working on a node.js app where I need to utilize setImmediate() to recursively call a function while maintaining its context for the next iteration. Let's take a look at an example: var i=3; function myFunc(){ console.log(i ...

Using JavaScript to insert a value through AJAX

I'm currently working on a website that displays the value of a .TXT file, and here is the progress I've made so far: <script> $(document).ready(function() { $("#responsecontainer").load("info.txt"); var refreshId = setInterval(function( ...

Navigate to the Bootstrap Panel body when the relevant link is clicked

I am facing an issue with a long list of panels that are tedious to scroll through. To make navigation easier, I am attempting to create a shortcut link at the top of the page. Below is the code for the shortcut: <a data-toggle="collapse" data-parent ...

How many intricate objects are instantiated in memory when running the code snippet provided above?

When looking at the given code, how many complex objects can we identify in memory? function Foo() { this.one = function() { return "one"; } } var f = new Foo(); Foo.two = function() { return "two"; }; Here's what I see: The Foo co ...