• 错误处理
    • 别忘了捕获错误
    • 不要忽略被拒绝的 promises

    错误处理

    错误抛出是个好东西!这使得你能够成功定位运行状态中的程序产生错误的位置。

    别忘了捕获错误

    对捕获的错误不做任何处理是没有意义的。

    代码中 try/catch 的意味着你认为这里可能出现一些错误,你应该对这些可能的错误存在相应的处理方案。

    反例:

    1. try {
    2. functionThatMightThrow();
    3. } catch (error) {
    4. console.log(error);
    5. }

    正例:

    1. try {
    2. functionThatMightThrow();
    3. } catch (error) {
    4. // One option (more noisy than console.log):
    5. console.error(error);
    6. // Another option:
    7. notifyUserOfError(error);
    8. // Another option:
    9. reportErrorToService(error);
    10. // OR do all three!
    11. }

    不要忽略被拒绝的 promises

    理由同 try/catch

    反例:

    1. getdata()
    2. .then(data => {
    3. functionThatMightThrow(data);
    4. })
    5. .catch(error => {
    6. console.log(error);
    7. });

    正例:

    1. getdata()
    2. .then(data => {
    3. functionThatMightThrow(data);
    4. })
    5. .catch(error => {
    6. // One option (more noisy than console.log):
    7. console.error(error);
    8. // Another option:
    9. notifyUserOfError(error);
    10. // Another option:
    11. reportErrorToService(error);
    12. // OR do all three!
    13. });