神刀安全网

“Error driven” software development

Error Driven Development

Instead of writing tests, you should write errors, and by that i mean, if there’s something wrong with the program, like unexpected behavior, it should "throw an error" : It should scream loud at your face (the developer): What the error is, in what source file and line number, and with a call stack, and state data.

If running in production, the error should be logged, and a developer notified. And the program/daemon instantly restarted.

Code examples

In JavaScript we get a lot "for free" . Throwing an error in JavaScript ( nodejs ) crashes the program and prints out a call stack. We can then provide the rest of the information in the Error message.

function addPerson(name, age) {  if(name.length < 1) throw new Error("name=" + name + " is only " + name.length + " characters long!");  if(age < 0 || age > 150) throw new Error("age=" + age + " is below zero or above 150!");    //... Some code here }  function disable(settings, option) {  if(!settings.hasOwnProperty(option) throw new Error("option=" + option + " does not exist in settings=" + JSON.stringify(Object.keys(settings)) );  //... Some code here  if(settings[option] != false) throw new Error("settings[" + option + "]=" + settings[option] + ", expected it to be false!"); }

Sometimes we do not want to crash though, but then we can use try-catch!

// Important that all these functions run var gotError = false; for(var=0; i<funs.length; i++) {  try {   funs[i](); // Execute the function  }  catch(err) {   console.warn("Error: " + err.message + "/n" + err.stack);   gotError = true;  } } if(gotError) throw new Error("Got error when running functions! See console log");

Written byJohan Zetterberg Mars 22, 2016.

Follow me via RSS:  

http://webtigerteam.com/johan/rss_en.xml (copy to feed-reader)

or Github:   “Error driven” software development https://github.com/Z3TA

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » “Error driven” software development

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮