How to write reusable errors?

时间:2018-07-24 10:09:38

标签: javascript error-handling throw

I have a function that evaluates an object, if its true, it pushes the object into an empty array if its false it needs to throw an error. How do I structure the Error so it's reusable, and can be overridden with some other message. Is it possible to not use the Try block?

const object1={
    title: "The Bridge",
    grade:  4.0,
    score: "Drama/Horrorr"
}

const object2={
    title:"Better Call Saul",
    score:7.0,
}
let shows=[];

function Add(param){
   if(param.hasOwnProperty("title") && 
      param.hasOwnProperty("score") &&
      param.hasOwnProperty("genre")) {
      shows.push(param);
      }
   else{
       throw "Object is missing a property !";
   }
   add(object1);
   add(object2);

   try{

   }
   catch(param){

   }

   Add(object1);
   Add(object2);

1 个答案:

答案 0 :(得分:0)

使用try / catch是javascript中最标准的方法。我会坚持这样做,而不是试图与潮流抗争。 抛出一个Error对象也是要抛出的标准对象

throw new Error('message')

或构造错误并为其添加属性

const err = new Error('message')
err.code = 1234
throw err

您可以从Error类派生一个类,并在其中添加自己的属性,如果您想获得更多可重用的内容。