记录下Vue中的try及Promise异常处理
Reverse Lv4

try...catch 结构

.then().catch() 结构

这两种结构都是用来处理异常的,但是有些不同,这里做个文档记录下,方便日后 CV

try 结构

  • 名称: try-catch 块
  • 作用: 用于处理同步代码中的异常。当 try 块中的代码执行时,如果发生异常,程序会跳过剩余的 try 块代码,直接执行 catch 块中的代码。

    示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let x = 10;

try {
let y = 20;
console.log(x + y); // 输出 30
// ...
} catch (error) {
console.error(error);
let z = 30; // z 只在 catch 块内有效
} finally {
console.log("Finally block executed");
}

console.log(z); // 报错,因为 z 仅在 catch 块内有效

try 块:

  • 作为独立的执行上下文。
  • 在 try 块中声明的变量仅在 try 块内有效。

catch 块:

  • 作为 try 块的子作用域。
  • 在 catch 块中声明的变量仅在 catch 块内有效。

finally 块:

  • 作为 try…catch 的子作用域。
  • 无论 try 或 catch 是否执行,finally 块都会执行。
  • 在 finally 块中声明的变量也仅在 finally 块内有效。

Promise 结构

  • 名称: Promise 的 then 和 catch 方法
  • 作用: 用于处理异步操作的结果。Promise 是一个代表异步操作最终完成(或失败)的对象,而 then 和 catch 方法则分别用于处理成功和失败的情况。
1
2
3
4
5
6
7
8
9
10
11
fetch("/api/data")
.then((response) => response.json())
.then((data) => {
console.log("成功获取数据:", data);
})
.catch((error) => {
console.error("获取数据失败:", error);
})
.finally(() => {
console.log("数据请求完成");
});

then():

  • 当 Promise 对象的状态变为 fulfilled(成功)时,就会调用 then 方法指定的回调函数。

catch():

  • 当 Promise 对象的状态变为 rejected(失败)时,就会调用 catch 方法指定的回调函数。

finally():

  • 无论 Promise 对象的状态是 fulfilled 还是 rejected,finally 方法指定的回调函数都会执行。