function mix(){
//console.log(arguments)
let answer;
let errorsArr=[];
let errorNew;
iterations: for( let i = 0 ; i < arguments.length; i ){
if(typeof arguments[i]!=='function'){
throw new Error('Every argument has to be function!')
}else{
try {
answer = arguments[i](answer);
} catch (error) {
errorNew = {name:`${error.name}`,message : `${error.message}`,stack:`${error.stack}`,level:`${error.level}`}
errorsArr.push(errorNew)
} finally{
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,square,divideTwo))
I had a homework to do a mix function to an unlimited arguments. it works perfectly if all arguments are functions but when any kind of error occurs it should handle and skip errored iteration without breaking program. how can I handle it correctly?
CodePudding user response:
Its the issue with your error handling section.
You should wrap your typeof arguments[i] !== "function"
statement inside a try catch
because its that place where you are throwing the error
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));
CodePudding user response:
Just catch throw new Error('Every argument has to be function!')
function mix(){
//console.log(arguments)
let answer;
let errorsArr=[];
let errorNew;
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) {
errorNew = {name:`${error.name}`,message : `${error.message}`,stack:`${error.stack}`,level:`${error.level}`}
errorsArr.push(errorNew)
}
}else{
answer = arguments[i](answer);
}
}
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,square,divideTwo, 2))