异步代码中的错误处理以及JS中的内置错误处理

异步代码中的错误处理

promise中的then…catch

可以使用then()和catch()链接多个 Promises,以处理链中单个 Promise 的错误

Promise.resolve(1)
  .then(res => {
      console.log(res);  // 打印 '1'
      throw new Error('something wrong');  // throw error
      return Promise.resolve(2);  // 这里不会被执行
  })
  .then(res => {
      // 这里也不会执行,因为错误还没有被处理
      console.log(res);    
  })
  .catch(err => {
      console.error(err.message);  // 打印 'something wrong'
      return Promise.resolve(3);
  })
  .then(res => {
      console.log(res);  // 打印 '3'
  })
  .catch(err => {
      // 这里不会被执行
      console.error(err);
  })

使用fetch调用API,该 API 返回一个promise对象,使用catch块处理 API 失败。

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

fetch("http://aaa.cn/500")
    .then(handleErrors)
    .then(response => console.log("ok"))
    .catch(error => console.log("Caught", error));
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)

try…catch 和 async await

在 async await 中 使用 try…catch

(async function() {
    try {
        await fetch("http://aaa.cn/500");
    } catch (err) {
        console.error(err.message);
    }
})();

使用fetch调用API,该API返回一个promise对象, 使用try…catch块处理API失败。

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
}

(async function() {
    try {
      let response = await fetch("http://aaa.cn/500");
      handleErrors(response);
      let data = await response.json();
      return data;
    } catch (error) {
        console.log("Caught", error)
    }
})();
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)
    at <anonymous>:11:7

JS 中的内置错误处理

Error

JavaScript 有内置的错误对象,它通常由try块抛出,并在catch块中捕获,Error 对象包含以下属性:

  • name:是错误的名称,例如 “Error”, “SyntaxError”, “ReferenceError” 等。
  • message:有关错误详细信息的消息。
  • stack:是用于调试目的的错误的堆栈跟踪。
const err = new Error('Error while executing the code');

console.log("name:", err.name); //name: Error
console.log("message:", err.message);//message: Error while executing the code
console.log("stack:", err.stack);
//stack: Error: Error while executing the code
//    at <anonymous>:1:13

EvalError

EvalError 表示关于全局eval()函数的错误,这个异常不再由 JS 抛出,它的存在是为了向后兼容。

RangeError

当值超出范围时,将引发RangeError。

> [].length = -1
ⓧ Uncaught RangeError: Invalid array length

ReferenceError

当引用一个不存在的变量时,将引发 ReferenceError。

> x = x + 1;
ⓧ Uncaught ReferenceError: x is not defined

SyntaxError

在 JS 代码中使用任何错误的语法时,都会引发SyntaxError。

> function() { return 'Hi!' }
ⓧ Uncaught SyntaxError: Function statements require a function name

> 1 = 1
ⓧ Uncaught SyntaxError: Invalid left-hand side in assignment

> JSON.parse("{ x }");
ⓧ Uncaught SyntaxError: Unexpected token x in JSON at position 2

TypeError

值不是预期的类型,会抛出TypeError。

> 1();
ⓧ Uncaught TypeError: 1 is not a function

> null.name;
ⓧ Uncaught TypeError: Cannot read property 'name' of null

URIError

以错误的方式使用全局 URI 方法,会抛出URIError。

> decodeURI("%%%");
ⓧ Uncaught URIError: URI malformed
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值