In Javascript, you can throw, instantiate a new Error(), and populate its custom properties all in a single line of code

Can all of this be done in a single line?

if (!user) {
    const error = new Error('Invalid user.')
    error.data = someObject
    error.code = 401
    throw error
}

Here's an example (with data and code properties populated)

if (!user) throw new Error('Invalid user.')

Answer №1

To customize the error object with additional properties, you can use the following approach:

if (!user) {
  throw Object.assign(new Error('Invalid user.'), {
    data: someObject,
    code: 401
  });
}

This method may not be a single line of code, but it demonstrates how to add custom properties to an error object.

For a more organized solution, consider creating your own class that extends Error to handle extra properties like data and code. (Refer to @Rajesh's suggestion)

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

Error: The function $.getScript(...).done cannot be found

Encountered a strange situation here.. . The following code is functioning properly: // this code working perfectly $.getScript( "https://wchat.freshchat.com/js/widget.js" ).done(( script, textStatus )=>{ // run something }); . . However, if ...

Utilize the client-side JavaScript file with ejs framework

Recently, I have been working on creating a website using Express and EJS. I discovered that using just one JavaScript file for all my EJS (view) files was causing issues. If I target a DOM element in one view page and it doesn't exist in another, I w ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Struggling with updating scope values when binding data in Angular (particularly with a slider)

Currently, I am utilizing Angular to develop a tool that can take user input from a slider tool and dynamically update an "estimate" field whenever the values are adjusted. However, I'm encountering an issue where the data is only binding in one direc ...

Combining HashRouter and anchor navigation in React: A guide to seamless page navigation

I am currently utilizing the HashRouter functionality from the library react-router-dom. The issue I am facing is when attempting to link to a specific div on the same page using an anchor tag: <a href="#div-id"> Link to div </a> In ...

Different ways to automatically trigger a function in JavaScript

There are various ways to trigger a function automatically in javascript when a page loads. I am interested in knowing which method is considered the most effective and reliable. If you have a unique approach that differs from others, please share it here ...

What is the best way to eliminate spaces, commas, and periods from a variable in javascript?

After attempting var res = str.replace(/ |,|.|/g, ""); and var res = str.replace(/ |,|.|/gi, "");, I'm still puzzled as to what I might be missing. var str = "Text with comma, space, and period."; var res = str.replace(/ |,|.|/g, ""); document.writ ...

Guide on displaying ajax data using PHP

I'm attempting to display the user-entered data by using AJAX to transfer it and then trying to print or echo it with PHP, but I'm having trouble getting it to work. enter code here Here is my code: <html> <head> <title> ...

Data retrieval error, function returned instead of expected value

Hey everyone, I'm currently working on fetching data using the GET method and I would like the data to be displayed after clicking a button, following standard CRUD operations. As a beginner in programming, I could use some help. Any assistance is gre ...

What is the best way to retrieve distinct id values from a form in Rails when sending a DELETE request via AJAX?

I am determined to grasp the intricacies of AJAX and how it operates, hence, I prefer not to use "remote: true" for this task. The issue at hand is that despite attempting to send a DELETE request to the server using a form input, each submission results i ...

I am experiencing unexpected results with my Mongoose filter and sort query in Express JS middleware. The output does not match what I am anticipating, and the sorting functionality seems to

This middleware is used for filtering and sorting data. I made some modifications to it, but it's not functioning as expected: const aliasTopMenu = (req, res, next) => { req.query.sort = '-price'; req.query.fields = 'name,price, ...

Animating elements within Firefox can sometimes cause adjacent elements to shift positions

Currently, I am working on a single-page website that utilizes keyboard-controlled scrolling. To achieve the desired scroll effect, I have developed a JavaScript function that animates divs. Here is the JavaScript code: var current_page = "#first"; func ...

Why won't my picture track the movement of the cursor?

I am trying to make my image follow the cursor using a specific code, but it doesn't seem to be working. I'm having trouble figuring out what's wrong with it. Here is the code snippet that I'm currently using: function followIt(e) ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...

Feeling lost when it comes to forms and hitting that submit button?

Below is a sample form structure: <html> <head> <title>My Page</title> </head> <body> <form name="myform" action="http://www.abcdefg.com/my.cgi" method="POST"> <div align="center"> <br><br; <br& ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

Unable to resolve an unresolved issue with a jquery or javascript bug

I am currently facing some issues with my jQuery code in both Firebug and Chrome's developer tools. Any assistance would be greatly appreciated. Kindly make the necessary updates in the provided fiddle. Please follow this link to access the fiddle: ...

Passing an array of integer arrays to a controller method in ASP MVC using Ajax

I am encountering an issue with my AJAX call when trying to post data entered by the user on the webpage to a controller method. Unfortunately, the data never reaches the controller and always results in an error. I suspect that the problem lies in the typ ...

Utilize JavaScript to extract and exhibit various SQL records stored within a multidimensional array

How can I use JS, JQuery, PHP, and MySQLi to automatically generate an HTML table within a div on a webpage? The table should display data based on user-input search criteria. For example, the user enters a start date and end date, clicks a button, which t ...