Send a personalized message to the error-catching block via throwing an error

I am trying to create a method for generating custom error messages that can be read within my catch block. My goal is to have the errorMessage variable in the catch block contain the message that is thrown by the throw Error function, allowing me to display a customized error message. However, I am running into issues when attempting to log the error (err).

const password = "test";
const repeatPassword = "test1";
let errorMessage = "";

const handleSubmit = () => {
    if(password != repeatPassword) {
    throw Error("Passwords must match");
  }
  
  try {
    console.log("trying");
  } catch(err) {
    errorMessage = err;
    console.log(err);
  }
}

handleSubmit();

Is my current approach incorrect?

Answer №1

rearrange your attempt as shown below

    const submitForm = () => {
      try {
        console.log("attempting");
        if(password != repeatPassword) {
        throw Error("Passwords need to be the same");
        }
      } catch(err) {
        errorMsg = err;
        console.log(err);
      }
    }

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

Next.js 13 React Server Component not displaying updated data upon build completion

I have a React Server Component that retrieves its data at build time and does not reload it while the site is running. I expected it to fetch the data once when the server component is first rendered. Is there a way to force this server component to relo ...

I must determine whether the contents of an array exceed zero

THE SUMMARY: I have three value numbers for an array. If the total addition of the array's elements is greater than 0, I need to display "el funcionamiento no es infinito", otherwise "es infinito". It seems that it's not working because I belie ...

Displaying colors using Javascript

When using node.js to create an HTML file from a js file, I am encountering an issue where the colors are not displaying in the output. I have generated hex values for the colors, but they do not appear in the HTML file as expected. var format; function ...

Guide on linking draggable elements

Currently, I have a set of div elements that I am able to clone and drag and drop into a specific area. Now, I am looking for a way to connect these divs with lines so that when I move the divs, the lines will also move accordingly. It's similar to cr ...

Updating the color with the help of useState in React, with the use of Material

I enjoy changing the color of the icon with a click using a useState hook. I have added a click handler to the icon for this purpose. Below is the code snippet: import React, { useState } from 'react'; import './App.css'; import ThumbU ...

Vue JS - Troubleshooting Checkbox Validation Error During Form Submission

When a user fills out my registration form, there is a checkbox to confirm acceptance of the terms and conditions. Currently, the validation error for this checkbox appears immediately upon hitting submit, even though the checkbox starts as unchecked. The ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

How can I detect if the browser's built-in object is available in Angular?

Exploring the Wechat JS API: The Wechat JS API relies on the WeixinJSBridge object within the Wechat built-in browser. This object is not immediately available upon opening the WebView; the client-side needs to initialize it. Once the WeixinJSBridge object ...

Utilize Javascript/Jquery to categorize JSON data based on the days of the week (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

A function is provided below that retrieves data for a chart. The output produced by this function is structured as follows: [Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, vo ...

"Retrieve the x-coordinate position of a box within a specific div using

https://i.sstatic.net/68yeF.jpg https://i.sstatic.net/ZCrxZ.jpg Is there a way for me to move the box within the gray area? <div id="timeline"> <div cdkDragBoundary="#timeline" ...

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

Learn the steps for filling the color area between two points in HighCharts

Is it possible to have a color fill between two points on an area chart when clicked? You can view the current chart here. $(function () { $('#container').highcharts({ chart: { type: & ...

Problem encountered when attempting to use 'delete' as a property name

I am currently encountering an issue with a form that deletes a gallery from a database. Previously, the code was functioning properly but after some recent updates such as switching from jquery.interface to jquery-ui, I am now facing difficulties. Wheneve ...

Troubleshooting AngularJS application by Manipulating List Items

Having trouble debugging Angular lately. It feels like things are breaking and fixing themselves magically. For instance, I had an ajax call to delete a "site" which was working fine until I decided to add some code to remove it from the list as well. Now, ...

Tips for consolidating all functions into a single file for ReactJS inheritance:

I'm curious about something. In Angular JS, we have the ability to create a global service file that can be inherited by every component. This allows us to use the functions written in the global service file within each respective component. Is ther ...

Could an element's loading be postponed on the initial page a user lands on?

One of my clients has requested a live chat system to be added to their website. I am fully capable of implementing it, and it is included through a script tag. Additionally, they have asked for a slight delay before the chat system loads in. My initial t ...

The element "Footer" cannot be found in the file path "./components/footer/Footer"

After attempting to run the npm start command, I encountered the following error. In my code, I am trying to import the file /components/footer/Footer.js into the file /src/index.js //ERROR: Failed to compile. In Register.js located in ./src/components/r ...

Arrange the given data either by ID or Name and present it

Here is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <style> .content{ border: 1px solid gray; width: 250px; ...

Problem encountered when attempting to post to a node/express endpoint

It has been a while since I last used JQuery/Ajax instead of axios to connect to an endpoint, am i making any mistakes here? var express = require('express'); var app = express() var bodyParser = require('body-parser'); var path = re ...

Error encountered in 11ty: Invalid operation - eleventyConfig.addPassthroughCopy is not a recognized function

Attempting to integrate my CSS and JavaScript codes into 11ty has been a bit challenging for me. I recently discovered that 11ty utilizes something called .11ty.js, so I decided to utilize the addPassthroughCopy() function. Below is the script I tried: mo ...