How to write reusable errors?

The name of the picture


How to write reusable errors?



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);





You can extend Error and build your own custom error classes.
– Xaqron
5 hours ago


Error




1 Answer
1



Using try/catch is the most standard approach in javascript. I would stick with that instead of trying to fight the tide.
throwing an Error object is also the standard object to throw


throw new Error('message')



or construct the error and add properties to it


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



You could derive a class from the Error class and add your own properties to it if you want something more reusable.


Error






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS