T
T
timonck2019-11-29 09:54:19
JavaScript
timonck, 2019-11-29 09:54:19

How to create custom errors in JS?

I have a point class, I need to create exceptions for it. Exceptions will appear if not numbers come into its arguments and if not 2 but more or less arguments come.

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

My version but it does not work correctly.
function isNum(num){
    if(typeof num.x !== Number || typeof num.y !== Number ){
        throw  new Error('point is not a number ')
    }
    console.log('isnm')
}

let exampleNum = new Point(1,1);
console.log(exampleNum)

try{
    isNum(exampleNum)
}catch(e){
    console.log("Something went wrong")
    console.error(e)
}

Tell me how to write the right exception?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wagoodoogoo, 2019-11-29
@timonck

class Point {
          constructor(x, y) {
              this.x = x;
              this.y = y;
          }

          isNum()
          {
              if(typeof this.x !== 'number' || typeof this.y !== 'number' ) {
                  throw new Error('point is not a number ')
              }
          }
      }


      try{
            let exampleNum = new Point(1,2)
            exampleNum.isNum()
          } catch(e){          
          console.error(e)
      }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question