Lanzar excepciones personalizadas en Javascript. ¿Qué estilo usar?
Douglas Crockford recomienda hacer algo como esto:
throw {
name: "System Error",
message: "Something horrible happened."
};
Pero también podrías hacer algo como esto:
function IllegalArgumentException(message) {
this.message = message;
}
throw new IllegalArgumentException("Argument cannot be less than zero");
y luego hacer:
try {
//some code that generates exceptions
} catch(e) {
if(e instanceof IllegalArgumentException) {
//handle this
} else if(e instanceof SomeOtherTypeOfException) {
//handle this
}
}
Supongo que podrías incluir untype
propiedad en la implementación de Crockford y luego examinar eso en lugar de hacer unainstanceof
. ¿Hay alguna ventaja de hacer uno contra el otro?