Is it possible to hurl an object within an Error in Javascript?

Can you toss an object via Error? This Script attempts to do so, resulting in the display of undefined on the console.

try {
    throw Error({foo: 'bar'});
} catch (err) {
    console.log(err.message.foo);
}

Answer №1

You have the option to hurl your very own object and couple it with an Error instance:

try {
  // ...
  throw {
    foo: "bar",
    error: new Error()
  };

The throw statement does not discriminate, but the Error() constructor does. However, if you toss something that is not an Error, it will be beneficial only if the catching environment anticipates it to be whatever you tossed.

Including the Error object in your custom thrown value proves advantageous because a created Error instance possesses (in compliant browsers, which currently appears to encompass nearly all) an attached stack trace.

Answer №2

If you are utilizing , it is possible to extend the ErrorConstructor interface and create your custom constructor that can accept an object in this format:

class CustomError extends Error {
  readonly id: number

  // the initial constructor only accepts a string as a message
  // by extending it, we can now pass an object including other data
  constructor({ id, name, message }) {
    super(message)
    this.name = name 
    this.id = id
  }
}

How to Use

function performAction() {
  if (errorOccurred) {
    throw new CustomError({
      id: 123,
      name: "custom_error",
      message: "An error has occurred",
    });
  }
}

try {
  performAction()
} catch (error) {
  if (error instanceof CustomError) {
    console.log("error id: " + error.id);
    console.log("error name: " + error.name);
    console.log("error message: " + error.message);
    alert(error.property); // name
  } else {
    // handle other types of errors
  }
}

Answer №3

If you want to handle errors by converting them to JSON format, one approach is to convert the object into a JSON string and then parse the error message back into a JSON object within the catch block:

try {
    throw new Error(JSON.stringify({name: 'John'}));
} catch (error) {
    console.log(JSON.parse(error.message).name);
}

Answer №4

If you encounter an issue, consider utilizing the cause property:

Currently, TypeScript may have inaccurate value types related to this, as seen in ongoing discussions on the official platform aimed at resolving it.

try {
     throw new Error('Encountered a failure', { 
       cause: {foo: 'bar'} 
     });
} catch(e) {
     console.log(e); // Error('Encountered a failure')
     console.log(e.cause) // {foo: 'bar'}
}

Alternatively, introduce a custom property when throwing the Error instance.

try {
     const error = new Error('Encountered a failure');
     error.foo = 'bar';
     throw error;
   } catch(e) {
     console.log(e); // Error('Encountered a failure')
     console.log(e.foo) // 'bar'
}

Answer №5

Why bother with JSON.stringify() and JSON.parse() when you can create your own property for the Error object? Instead of passing the object to the message parameter, which only accepts a string, try this approach:

try {
  let error = new Error();
    
  Object.assign(error, { foo: 'bar' });

  throw error;
} catch (err) {
  console.log(err.foo);
}

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

Build an immersive experience by incorporating threejs into A-Frame to develop a spherical environment filled with 360-degree videos

I've been working on a VR project that involves 360° videos in VR. My concept was to construct a sphere and apply a 360° video as the material. I've already managed to create my own Sphere Component and map a 360° image onto it! Similar to t ...

Adding double quotes to arrays in D3.js after using the .map method

Here is the code snippet I am working with: d3.csv("static/data/river.csv", function(data) { var latlongs = data.map(function(d) { return [d.Lat,d.Lng]; }) var lineArray1 = latlongs; console.log(lineArray1); When I view the outpu ...

A guide to extracting value from an input field with the power of JavaScript

I am currently facing an issue retrieving values from input fields. Some of these input fields are a result of a calculation process, such as #t1_potensi and #t2_potensi, while #aliran is the outcome of the overall calculation process. Below is my HTML co ...

Querying the children of an element using jQuery

$('.Title').children(function() { var titleValue = $('.Title').text(); console.log(titleValue); }); Wondering how to access all children with the 'title' tag and log their values individually. ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Managed the double-click event to select Snap.svg text

I am currently utilizing the snapsvg library for a project where I am implementing the dblclick event to trigger a browser window alert. However, when clicking on the svg canvas, not only does the alert pop up but some text on the canvas also gets selected ...

Anonymous self-executing functions with parameters from an external scope

Recently, I stumbled upon the code snippet below while following a tutorial. const increment = (function(){ return function incrementbytwo (number){ return number+2; } })(); console.log(increment(1)); The result of the code above is 3. ...

receiving "null" values when retrieving data from LocalStorage using the getItem method

I am facing an issue in my application where I need to pass the Email value from the login component to the dashboard component. Both components are separate entities. In the login component, I have saved the values in local storage using setItem as shown ...

How can TypeScript objects be serialized?

Is there a reliable method for preserving type information during JSON serialization/deserialization of Typescript objects? The straightforward JSON.parse(JSON.stringify) approach has proven to have several limitations. Are there more effective ad-hoc sol ...

What is the best way to combine elements in an array of strings using commas between each item, but using "and" before the last item?

I have a collection of phrases that looks like this. ['white t-shirt', 'blue jeans', 'red hat', 'brown glasses'...] I am looking for a way to insert these phrases into the text below, separated by commas, with the w ...

What is the best way to integrate properties subsets into your classes?

In my code, I am working with 3 classes ... class1 { constructor(a, b, c) { this.a = a; this.b = b; this.c = c; this.toClass2 = function() { // TODO: return this as an instance of class2; // the conversion would remove the un ...

retrieve the path of any module within an npm monorepo

I am working on a project using an NPM monorepo structure which utilizes ECMAScript Modules (ESM): <root> |_package.json |_node_modules/ | |_luxon (1.28.0) |_packages/ |_pack1 | |_node_modules/ | | |_luxon (3.0.1) | |_main.js |_pack2 |_ ...

Hiding the filelist on antd-Upload when the URL is not provided

When passing a Url as a prop to display uploaded files in an edit Modal, I want to ensure that no attachments are shown if the Url is empty. Currently, I am still seeing empty attachments displayed as shown in the image: https://i.sstatic.net/dkzu1.png ex ...

Deploying a React App to Github Pages Results in a Blank Screen

After successfully uploading a simple react app onto GitHub pages using gh-pages, I attempted to import the Shards dashboard project (https://github.com/DesignRevision/shards-dashboard-react) onto my GitHub page. Unfortunately, all I see is a blank page. ...

Prior to the image being loaded, the JQuery load() function is triggered

I am facing an issue where I want to change the src attribute of my image and then retrieve the width of the new image. The problem is that the JQuery load() function seems to execute before the image is fully loaded and its width is determined. Any sugges ...

Do the jQuery fadeIn() and animation() functions operate in a non-blocking manner?

When my page loads, it initiates multiple ajax queries using $('document').ready(). I want to incorporate fadeIn() or animation() to briefly display some information after the first ajax call is received. Would the subsequent js/ajax calls be he ...

Refreshing a React page will lead to props being empty

The situation I am facing is that the code appears to be correct, but for some reason, when the web page loads, this.props.items does not seem to be passed to Item. Strangely, when I attempt to display this.props.items in console.log, nothing shows up. How ...

Exploring the possibilities of applying a fragmentShader texture to repeat a ThreeJS Matcap

Here are the vertex and fragment shader materials: material = new THREE.ShaderMaterial( { uniforms: { textureMap: { type: 't', value: THREE.ImageUtils.loadTexture( 'img/matcap/green.jpg' ) }, normalMap: { type: 't' ...

How come my function is executing right away despite the setTimeout() being called?

I am working on a program that is designed to showcase how a bubble sort works. However, I would like the program to pause for one second after each swap in order to clearly demonstrate the sorting process. Below is the code I have written: function bubble ...

Issue: Unable to find suitable routes for navigation. URL Segment: 'profile' or Encounter: Server could not load resource as response status is 401 (Unauthorized)

Currently, I am working on the MEANAUTH application and encountering an issue with accessing user profiles using angular jwt. When attempting to log in and access user profiles at https://localhost:3000/profile, I receive the following error message: Faile ...