• 【JavaScript】try/catch和Promise.catch捕捉错误的区别?


    【JavaScript】try/catch和Promise.catch捕捉错误的区别?

    前言

    try/catch 语句 和 Promise catch() 方法捕获错误的方式有所不同。
    try/catch 捕获的是同步错误,即同步任务产生的错误。

    try/catch

    • 同步任务未使用 try/catch 语句包裹,则 JavaScript 运行时会暂停在使用 throw 关键字抛出错误的地方。
    console.log('开始同步任务')
    throw Error('出错了')
    console.log('结束同步任务')
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    • 同步任务使用 try/catch 语句包裹,则不影响抛出错误后,后续代码逻辑的执行。
    console.log('开始同步任务')
    try {
      throw Error('出错了')
    } catch (error) {
      console.log('try catch捕获同步错误', error)
    }
    console.log('结束同步任务')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    阶段总结

    • throw 关键字抛出错误后, JavaScript 运行时会暂停在使用 throw 关键字抛出错误的地方。
    • try/catch 语句包裹可能抛出错误的同步任务,则不会阻止运行时的继续执行。

    Promise.catch

    • Promise 抛出错误,并不会阻止运行时继续执行同步任务。
    console.log('开始同步任务')
    Promise.reject(Error('出错了'))
    console.log('结束同步任务')
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    • Promise 抛出错误并使用 catch() 方法捕获。
    new Promise((resolve, reject) => {
      console.log('开始同步任务')
      reject(Error('出错了'))
    }).catch(e => {
      console.log('Promise catch捕获异步错误', e)
    }).then(() => {
      console.log('继续同步任务')
    })
    console.log('结束同步任务')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    • Promise 抛出错误并使用 try/catch 语句捕获。
    try {
      new Promise((resolve, reject) => {
        console.log('开始同步任务')
        reject(Error('出错了'))
      })
    } catch (error) {
      console.log('try catch捕获同步错误', error)
    }
    console.log('结束同步任务')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    • Promise 抛出错误并使用 try/catch 语句和 catch() 方法捕获。
    try {
      new Promise((resolve, reject) => {
        console.log('开始同步任务')
        reject(Error('出错了'))
      }).catch(e => {
        console.log('Promise catch捕获异步错误', e)
      }).then(() => {
        console.log('继续同步任务')
      })
    } catch (error) {
      console.log('try catch捕获同步错误', error)
    }
    console.log('结束同步任务')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述

    阶段总结

    • try/catch 语句只能捕获同步错误,无法捕获 Promise 抛出的异步错误。
    • 同理,try/catch 亦不能捕获 async 异步函数抛出的错误。
    • async 异步函数抛出的错误无法被 try/catch 语句捕获
    async function fn () {
      throw Error('出错了')
    }
    try {
      console.log('开始同步任务')
      fn()
    } catch (error) {
      console.log('try catch捕获同步错误', error)
    }
    console.log('结束同步任务')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    ![在这里插入图片描述](https://img-blog.csdnimg.cn/bffb64d7626349059ce7f0f9009688c1.png

    • async 异步函数抛出的错误,经过 await 关键字处理后,会暂停异步函数后面的代码,使该异步函数以同步的方式执行,故可以被
      try/catch 语句捕获。
    async function fn () {
      throw Error('出错了')
    }
    try {
      console.log('开始同步任务')
      await fn()
    } catch (error) {
      console.log('try catch捕获同步错误', error)
    }
    console.log('结束同步任务')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在这里插入图片描述

    关于 async/awaitPromise 的区别,另有一文介绍
    【JavaScript】Promise和async/await的区别

    实际应用

    console.log('开始同步任务')
    let loading = false
    function getUser () {
      return new Promise((resolve, reject) => {
        setTimeout(reject, 1000, '出错了');
      })
    }
    try {
      loading = true
      const user = await getUser()
      loading = false
    } catch (error) {
      // loading = false // 重要!!!重置loading
      console.log('try catch捕获同步错误', error, 'loading =', loading)
    }
    console.log('结束同步任务,loading =', loading)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    console.log('开始同步任务')
    let loading = false
    function getUser () {
      return new Promise((resolve, reject) => {
        setTimeout(reject, 1000, '出错了');
      })
    }
    loading = true
    let user = null
    getUser().then(res => {
      loading = false
      user = res
    }).catch(e => {
      loading = false // 重要!!!重置loading
      console.log('Promise catch捕获异步错误', e, 'loading =', loading)
    })
    console.log('结束同步任务,loading =', loading)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

    总结

    • try/catch 语句捕获同步任务产生的错误。
    • Promise catch() 方法捕获异步任务阐释的错误。
    • async 关键字声明的异步函数,在经过 await 关键字处理后,抛出的错误可以被 try/catch 语句捕获。
  • 相关阅读:
    Android自定义Drawable---灵活多变的矩形背景
    vue基础语法
    ML Design Patterns——Models and Framework
    SpringBoot 集成 RabbitMq 实现五种常用消息模型
    带你玩转 Redis 的 SortedSet 数据类型
    【温故而知新】构建高可用Linux服务器(三)
    Array.from()的使用方法(数组去重,伪数组转为数组,数组浅克隆),Set和Map数据结构
    Spring Boot 3.2四个新特点提升运行性能
    【Java集合】HashMap系列(四)——HashMap在JDK1.7和JDK1.8中的并发问题的分析以及如何保证并发安全
    MySQL监控主从复制
  • 原文地址:https://blog.csdn.net/harmsworth2016/article/details/125471841