Individua più tipi di errori in javascript [duplicato]
Aug 16 2020
Se definisco classi di errore personalizzate come questa:
class MyCustom Error extends Error{ }
Come posso rilevare più errori come questo:
try{
if(something)
throw MyCustomError();
if(something_else)
throw Error('lalala');
}catch(MyCustomError err){
}catch(err){
}
?
Il codice precedente non funziona e fornisce alcuni errori di sintassi
Risposte
1 TheOtterlord Aug 16 2020 at 15:37
La documentazione MDN consiglia di utilizzare un if/else
blocco all'interno catch
dell'istruzione. Questo perché è impossibile avere più catch
istruzioni e non è possibile rilevare errori specifici in questo modo.
try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}
1 Hi-IloveSO Aug 16 2020 at 15:38
JavaScript è digitato in modo debole. Utilizzare if (err instanceof MyCustomError)
all'interno della clausola catch.