skip to Main Content

Below is a simplification of how my code is

class A {
 public static doCleanup() { ... }
}

class B {
 public run() {
  try {
    this.doSomeWork();
  } catch(err) {
    console.log(err);
  }
 }

 doSomeWork() {
  // Does something and when encounters a error
  throw this.myError(someArgs);
 }

 myError(someArgs) {
   A.doCleanup();
   console.log('HI');
   return new CustomError();
 }
}

let foo = new B();
foo.run();

When I run this code, in the doSomeWork when the throw statement is executed, myError function doesn’t run, but instead the control immediately goes inside the catch block.
But if I remove the A.doCleanup() line myError runs fine without any issue.
What is happening?

2

Answers



  1. You haven’t define customError class in your code

    Your code should be like this:

    class A {
      static doCleanup() {
        // ... your cleanup logic here
        console.log('Clean up performed');
      }
    }
    
    class B {
      run() {
        try {
          this.doSomeWork();
        } catch (err) {
          console.log(err);
        }
      }
    
      doSomeWork() {
        // Does something and when encounters an error
        throw this.myError('someArgs');
      }
    
      myError(someArgs) {
        A.doCleanup();
        console.log('HI');
        return new CustomError(someArgs);
      }
    }
    
    class CustomError extends Error {
      constructor(message) {
        super(message);
        this.name = 'CustomError';
      }
    }
    
    let foo = new B();
    foo.run();
    
    Login or Signup to reply.
  2. The issue is with the code written in the A.doCleanup method.
    For some reason, it’s throwing an error and that’s why your CustomError is not getting called.

    This is the reason why when you remove the A.doCleanup() line myError runs fine without any issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search