0

I have a class, I would like an error method to return a way to handle it from the object

class MyClass {
On(value){
     try{
     throw new Error("Massimo due candidati");
      }
      catch(e){
              console.log(e.name, e.message); //Error, I'm Evil
      }
}
}

If I create an object of the class how can I handle the error in a similar way?

var obj = new MyClass();
obj.on(value, err=> {
if (err) {
    onError(err.message);
  }else{
    console.log("Inserimento ok");
  }
});

Thanks for your attention.

2 Answers 2

1

When .on is called, push the callback to an array of callbacks stored by the object. Then, whenever whatever triggers the .on runs, iterate through all callbacks in the array and invoke them (and possibly pass an error argument too):

class MyClass {
  onCallbacks = [];
  on(someArg, callback) {
    this.onCallbacks.push(callback);
  }
  invokeOK() {
    this.onCallbacks.forEach((callback) => {
      callback();
    });
  }
  invokeError() {
    this.onCallbacks.forEach((callback) => {
      callback(new Error('foo'));
    });
  }
}

const onError = console.error;
const obj = new MyClass();
obj.on('value', err => {
  if (err) {
    onError(err.message);
  } else {
    console.log("Inserimento ok");
  }
});

obj.invokeError();
obj.invokeOK();

Sign up to request clarification or add additional context in comments.

Comments

0

thanks for your help. I think in my head I wanted to do this ...

class MyClass {
  onCallbacks = [];
  on(someArg, callback) {
    if (someArg != 'value') {
        this.onCallbacks.push(callback);
    }else{
    console.log("start ok");
    }
  }
  invokeOK() {
  //if (this.onCallbacks.length==0){return;}
    this.onCallbacks.forEach((callback) => {
      callback();
    });
  }
  invokeError() {
    this.onCallbacks.forEach((callback) => {
      callback(new Error('foo'));
    });
  }
}

const onError = console.error;
const obj = new MyClass();

obj.on('value', err => {
  if (err) {
    onError(err.message);
    console.log(err.message);
  }
});
obj.invokeError();
obj.invokeOK();

If it seems wrong to you as a process, let me know.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.