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);
}
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);
}
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.
If you are utilizing typescript, 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
}
}
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
}
}
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);
}
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'
}
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);
}
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 ...
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 ...
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 ...
$('.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. ...
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: ...
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 ...
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. ...
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 ...
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 ...
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 ...
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 ...
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 |_ ...
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 ...
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. ...
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 ...
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 ...
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 ...
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' ...
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 ...
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 ...