Lançando exceções personalizadas em JavaScript. Qual estilo usar?
Douglas Crockford recomenda fazer algo assim:
throw {
name: "System Error",
message: "Something horrible happened."
};
Mas você também pode fazer algo assim:
function IllegalArgumentException(message) {
this.message = message;
}
throw new IllegalArgumentException("Argument cannot be less than zero");
e então faça:
try {
//some code that generates exceptions
} catch(e) {
if(e instanceof IllegalArgumentException) {
//handle this
} else if(e instanceof SomeOtherTypeOfException) {
//handle this
}
}
Eu acho que você poderia incluir umtype
propriedade na implementação de Crockford e, em seguida, examinar que, em vez de fazer uminstanceof
. Existe alguma vantagem de fazer um versus o outro?