What methods can be used to manage errors and smoothly continue with the function in JavaScript?

function combine(){
    //console.log(arguments)
    let result;
    let errors=[];
    let newError;
    iterations: for( let i = 0 ; i < arguments.length; i++){
        if(typeof arguments[i]!=='function'){
            throw new Error('Each argument must be a function!')
        }else{
                try {
                    result = arguments[i](result); 
                    
                } catch (error) {
                    newError = {name:`${error.name}`,message : `${error.message}`,stack:`${error.stack}`,level:`${error.level}`}
                    errors.push(newError)
                   
                } finally{
                    continue iterations;
                }

        }
    }
    const finalResult = {
        errors :errors,
        value: result
    }

    return finalResult;
    
}


function square(n){
    return n*2
}
function million(){
    return  1000000
}
function divideTwo(n){
    return n/2;
}


console.log(combine(million,square,divideTwo))

I was tasked with creating a combine function that can take an unlimited number of arguments. It functions correctly when all arguments are functions, but if an error occurs, it should handle it and skip the iteration without breaking the program. How can I handle this scenario correctly?

Answer №1

Simply catch the error:

throw new Error('Every argument must be a function!')

function combine(){
    //console.log(arguments)
    let response;
    let errorsArray=[];
    let newError;
    iterations: for( let i = 0 ; i < arguments.length; i++){
        if(typeof arguments[i]!=='function'){
         try {
            throw new Error('Every argument has to be function!')
              } catch (error) {
                    newError = {name:`${error.name}`,message : `${error.message}`,stack:`${error.stack}`,level:`${error.level}`}
                    errorsArray.push(newError)
                   
                }
        }else{
               
                    response = arguments[i](response); 
                    
        

        }
    }
    const resultObject = {
        errors :errorsArray,
        value: response
    }

    return resultObject;
    
}


function multiplyByTwo(n){
    return n*2
}
function getMillion(){
    return 1000000
}
function divideByTwo(n){
    return n/2;
}


console.log(combine(getMillion, multiplyByTwo, divideByTwo, 2))

Answer №2

There seems to be an issue in the error handling section of your code.

To address this, it is recommended to enclose the

typeof arguments[i] !== "function"
statement within a try catch block as this is where the errors are being thrown.

function mix() {
  console.log(arguments);
  let answer;
  let errorsArr = [];
  let errorNew;
  iterations: for (let i = 0; i < arguments.length; i++) {
    try {
      if (typeof arguments[i] !== "function") {
        throw new Error("Every argument has to be function!");
      } else {
        answer = arguments[i](answer);
      }
    } catch (error) {
      errorNew = {
        name: `${error.name}`,
        message: `${error.message}`,
        stack: `${error.stack}`,
        level: `${error.level}`,
      };
      errorsArr.push(errorNew);
      continue iterations;
    }
  }
  const returnedObject = {
    errors: errorsArr,
    value: answer,
  };

  return returnedObject;
}

function square(n) {
  return n * 2;
}
function million() {
  return 1000000;
}
function divideTwo(n) {
  return n / 2;
}

console.log(mix(million, 5, square, divideTwo));

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

Protractor - Chrome is denying access to this webpage when attempting to access it automatically

Currently, I am familiarizing myself with Protractor as the tool for automating website testing. Specifically, I am running tests on the following page: , using Google Chrome browser. The issue at hand is: 1. Protractor successfully navigates to . 2. Ma ...

Guide to uploading a JavaScript File object to Cloudinary via the node.js API

After researching various options, I decided to use cloudinary for uploading a file to an image server from my node js api. I successfully installed the npm package for cloudinary and implemented the code based on their api documentation Below is the fun ...

Instead of pushing multiple items, focus on pushing only one item at a time

I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist. However, instead of adding the new item only once, it ends up being added multiple times. What would be ...

Is there a way to connect and interact with a different ng-controller's ng-model within a separate ng-controller?

Is it possible to access the ng-model from another ng-controller and if so, how can it be done? In this scenario, I am using two controllers. The first controller has a model called mddl1, while the second controller does not have any other model. However, ...

Error in Asp.Net Mvc Bundle: Incorrect Path for Scripts

In my ASP. NET MVC Project, I have set up BundleConfig to include jquery, bootstrap, and modernizr scripts. Everything works well when running locally, with the path leading to the exact .js file. However, when I publish the project to the hosting server, ...

Accessing iPhone photo galleries through web browsers using HTML5 technology

I'm looking for a way to interact with the camera roll and photo library on iPhone/iPad using only HTML5 and JavaScript in the browser. I want to create a web app without relying on PhoneGap at this stage. Currently, I can capture a picture from the ...

Implementing auto-complete functionality using two keys in Material UI and React

My goal is to enable autocomplete for input when searching with values like title and year. Strangely, the autocomplete feature only works when I search with title. Searching with year does not yield any options. Sample code export default function ComboB ...

Creating designs on the canvas

With this code snippet, I have the ability to create lines using mouse points on a canvas. My goal is to identify when these lines connect to form a shape and then fill that shape with color. <script language="javascript" src="//ajax.googleapis.com/a ...

Upon reaching a specific milestone on the page, automatically scroll to the designated anchor point

Here's the deal: I plan to showcase 4 divs on my page. Each div will have a specific height (around 1500px) but will span the full width of the screen. To add some flair, each div will be a different color. My goal is for JavaScript to kick in once ...

Determine the quantity of classes based on the part name

I have the code snippet provided below: <ul id="towns"> <li class="clearfix odd 516_499_132_0_0 town132">...</li> </ul> I am looking to extract the specific class "town132" as a parameter, but the number - such as 132 in this ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...

Creating responsive arrow heads using D3: A step-by-step guide

Currently, I am working on creating a thermometer-style bar chart using D3.js version 3. While I have successfully created a basic responsive rectangle with two filled colors, I am facing difficulties in figuring out how to add arrow heads to the design. B ...

How can I display the Bootstrap 5.3.0 Collapsible button on this basic website?

I've been struggling to implement a Bootstrap Collapsible on my web page using Bootstrap version 5.3.0. I've tried different approaches but I can't seem to get it to work. All I need is a Collapsible that contains a few links, which should b ...

Can an App be duplicated from Chrome sources even if it displays all files except for the package.json?

I recently came across a React platform that I would like to dissect in order to gain a deeper understanding of it and potentially redesign it for a future project. Though the platform seems to have all the necessary files, I am unsure if I may be missing ...

What is the best way to extract the object from a button's value?

My method involves using the map function on an array containing objects in order to generate a button: arrayOfObjects.map(obj => ( <button value={obj} onClick={handleClick} key={obj._id}> {obj.name} </button> This is how it works: ...

What is the best way to switch between 3 components in ReactJS?

I'm facing a challenge with conditionally rendering components in React. I've managed to render two components (A and B) based on certain conditions, but I'm struggling to implement a third component (C) in this scenario. Here's the co ...

Every time I adjust my query, I consistently receive an incorrect response from the initial result

Currently, I am working on server-side programming using Node.js native. The code I have written is located in the `server.js` file and looks like this: const express = require('express'); const https = require('https'); const bodyParse ...

iPhone: Fixed position div disappearing

Currently, I am working on creating a mobile menu for my Joomla 3 site located at . The menu is functioning correctly on desktops, however, when attempting to view it on my iPhone, the menu slides in but remains invisible. Despite this, I can still tap on ...

The ng-html-to-pdf-save feature does not function properly when using Persian or Arabic characters

I am trying to utilize this module to print Persian content, but unfortunately, the characters are not displaying correctly. Here is the code snippet I am using: <script type="text/ng-template" id="patient_modal.html"> <div class="modal-heade ...

Creating test cases for an undefined window Object in Vue test utils using the Jest Framework

Vue test utils along with the Jest framework is what I'm using for unit testing my vue file. For some reason, I'm facing difficulties in testing the following line of code: const inBrowser = typeof window !== 'undefined'; My main quer ...