- 错误处理
- 别忘了捕获错误
- 不要忽略被拒绝的 promises
错误处理
错误抛出是个好东西!这使得你能够成功定位运行状态中的程序产生错误的位置。
别忘了捕获错误
对捕获的错误不做任何处理是没有意义的。
代码中 try/catch 的意味着你认为这里可能出现一些错误,你应该对这些可能的错误存在相应的处理方案。
反例:
try {functionThatMightThrow();} catch (error) {console.log(error);}
正例:
try {functionThatMightThrow();} catch (error) {// One option (more noisy than console.log):console.error(error);// Another option:notifyUserOfError(error);// Another option:reportErrorToService(error);// OR do all three!}
不要忽略被拒绝的 promises
理由同 try/catch。
反例:
getdata().then(data => {functionThatMightThrow(data);}).catch(error => {console.log(error);});
正例:
getdata().then(data => {functionThatMightThrow(data);}).catch(error => {// One option (more noisy than console.log):console.error(error);// Another option:notifyUserOfError(error);// Another option:reportErrorToService(error);// OR do all three!});
