try..catch 不能捕获的错误有哪些?注意事项又有哪些?

更新日期: 2020-11-09阅读: 1.3k标签: 错误

今天的内容中,我们来学习一下使用try、catch、finally和throw进行错误处理。我们还会讲一下 JS 中内置的错误对象(Error, SyntaxError, ReferenceError等)以及如何定义自定义错误。


1.使用 try..catch..finally..throw

在 JS 中处理错误,我们主要使用try、catch、finally和throw关键字。

  • try块包含我们需要检查的代码
  • 关键字throw用于抛出自定义错误
  • catch块处理捕获的错误
  • finally 块是最终结果无论如何,都会执行的一个块,可以在这个块里面做一些需要善后的事情

1.1 try

每个try块必须与至少一个catch或finally块,否则会抛出SyntaxError错误。

我们单独使用try块进行验证:

try {
  throw new Error('Error while executing the code');
}
ⓧ Uncaught SyntaxError: Missing catch or finally after try

1.2 try..catch

建议将try与catch块一起使用,它可以优雅地处理try块抛出的错误。

try {
  throw new Error('Error while executing the code');
} catch (err) {
  console.error(err.message);
}
➤ ⓧ Error while executing the code

1.2.1 try..catch 与 无效代码

try..catch 无法捕获无效的 JS 代码,例如try块中的以下代码在语法上是错误的,但它不会被catch块捕获。

try {
  ~!$%^&*
} catch(err) {
  console.log("这里不会被执行");
}
  Uncaught SyntaxError: Invalid or unexpected token

1.2.2 try..catch 与 异步代码

同样,try..catch无法捕获在异步代码中引发的异常,例如setTimeout:

try {
  setTimeout(function() {
    noSuchVariable;   // undefined variable
  }, 1000);
} catch (err) {
  console.log("这里不会被执行");
}

未捕获的ReferenceError将在1秒后引发:

➤ ⓧ Uncaught ReferenceError: noSuchVariable is not defined

所以 ,我们应该在异步代码内部使用 try..catch 来处理错误:

setTimeout(function() {
  try {
    noSuchVariable;
  } catch(err) {
    console.log("error is caught here!");
  }
}, 1000);

1.2.3 嵌套 try..catch

我们还可以使用嵌套的try和catch块向上抛出错误,如下所示:

try {
  try {
    throw new Error('Error while executing the inner code');
  } catch (err) {
    throw err;
  }
} catch (err) {
  console.log("Error caught by outer block:");
  console.error(err.message);
}
Error caught by outer block:
➤ ⓧ Error while executing the code

1.3 try..finally

不建议仅使用 try..finally 而没有 catch 块,看看下面会发生什么:

try {
  throw new Error('Error while executing the code');
} finally {
  console.log('finally');
}
finally
➤ ⓧ Uncaught Error: Error while executing the code

这里注意两件事:

  • 即使从try块抛出错误后,也会执行finally块
  • 如果没有catch块,错误将不能被优雅地处理,从而导致未捕获的错误

1.4 try..catch..finally

建议使用try...catch块和可选的finally块。

try {
  console.log("Start of try block");
  throw new Error('Error while executing the code');
  console.log("End of try block -- never reached");
} catch (err) {
  console.error(err.message);
} finally {
  console.log('Finally block always run');
}
console.log("Code execution outside try-catch-finally block continue..");
Start of try block
➤ ⓧ Error while executing the code
Finally block always run
Code execution outside try-catch-finally block continue..

这里还要注意两件事:

  • 在try块中抛出错误后往后的代码不会被执行了
  • 即使在try块抛出错误之后,finally块仍然执行

finally块通常用于清理资源或关闭流,如下所示:

try {
  openFile(file);
  readFile(file);
} catch (err) {
  console.error(err.message);
} finally {
  closeFile(file);
}

1.5 throw

throw语句用于引发异常。

throw <expression>
// throw primitives and functions
throw "Error404";
throw 42;
throw true;
throw {toString: function() { return "I'm an object!"; } };

// throw error object
throw new Error('Error while executing the code');
throw new SyntaxError('Something is wrong with the syntax');
throw new ReferenceError('Oops..Wrong reference');

// throw custom error object
function ValidationError(message) {
  this.message = message;
  this.name = 'ValidationError';
}
throw new ValidationError('Value too high');


2. 异步代码中的错误处理

对于异步代码的错误处理可以Promise和async await。

2.1 Promise 中的 then..catch

我们可以使用then()和catch()链接多个 Promises,以处理链中单个 Promise 的错误,如下所示:

Promise.resolve(1)
  .then(res => {
      console.log(res);  // 打印 '1'

      throw new Error('something went wrong');  // throw error

      return Promise.resolve(2);  // 这里不会被执行
  })
  .then(res => {
      // 这里也不会执行,因为错误还没有被处理
      console.log(res);    
  })
  .catch(err => {
      console.error(err.message);  // 打印 'something went 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://httpstat.us/500")
    .then(handleErrors)
    .then(response => console.log("ok"))
    .catch(error => console.log("Caught", error));
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)

2.2 try..catch 和 async await

在 async await 中 使用 try..catch 比较容易:

(async function() {
    try {
        await fetch("http://httpstat.us/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://httpstat.us/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


3. JS 中的内置错误

3.1 Error

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

  • name:是错误的名称,例如 “Error”, “SyntaxError”, “ReferenceError” 等。
  • message:有关错误详细信息的消息。
  • stack:是用于调试目的的错误的堆栈跟踪。

我们创建一个Error 对象,并查看它的名称和消息属性:

const err = new Error('Error while executing the code');

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

JavaScript 有以下内置错误,这些错误是从 Error 对象继承而来的

3.2 EvalError

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

3.3 RangeError

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

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

3.4 ReferenceError

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

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

3.5 SyntaxError

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

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

➤ 1 = 1
ⓧ Uncaught SyntaxError: Invalid left-hand side in assignmentJSON.parse("{ x }");
ⓧ Uncaught SyntaxError: Unexpected token x in JSON at position 2

3.6 TypeError

如果该值不是预期的类型,则抛出TypeError。

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

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

3.7 URIError

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

decodeURI("%%%");
ⓧ Uncaught URIError: URI malformed


4. 定义并抛出自定义错误

我们也可以用这种方式定义自定义错误。

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  } 
};

const err = new CustomError('Custom error while executing the code');

console.log("name:", err.name);
console.log("message:", err.message);
name: CustomError
message: Custom error while executing the code

我们还可以进一步增强CustomError对象以包含错误代码

class CustomError extends Error {
  constructor(message, code) {
    super(message);
    this.name = "CustomError";
    this.code = code;
  } 
};

const err = new CustomError('Custom error while executing the code', "ERROR_CODE");

console.log("name:", err.name);
console.log("message:", err.message);
console.log("code:", err.code);
name: CustomError
message: Custom error while executing the code
code: ERROR_CODE

在try..catch块中使用它:

try{
  try {
    null.name;
  }catch(err){
    throw new CustomError(err.message, err.name);  //message, code
  }
}catch(err){
  console.log(err.name, err.code, err.message);
}
CustomError TypeError Cannot read property 'name' of null

原文:https://codings.com/


链接: https://www.fly63.com/article/detial/10054

解决Cannot read property range of null 错误

vue工程npm run serve/start/dev启动时,node_modules文件报:Cannot read property range of null 错误,该问题是babel-eslint版本更新问题导致的;

HTTP 400 错误 - 请求无效 (Bad request)

在ajax请求后台数据时有时会报 HTTP 400 错误 - 请求无效 (Bad request);出现这个请求无效报错说明请求没有进入到后台服务里;原因:前端提交数据的字段名称或者是字段类型和后台的实体类不一致

js异步错误捕获

我们都知道 try catch 无法捕获 setTimeout 异步任务中的错误,那其中的原因是什么。以及异步代码在 js 中是特别常见的,我们该怎么做才比较?

不能执行已释放Script的代码

父页面初始化声明变量a为数组(数组对象是引用类型,赋值传递的是地址),创建iframe子页面后给父页面变量a赋值,赋值后销毁iframe子页面,再次调用变量a的时候就会抛出异常‘SCRIPT5011:不能执行已释放Script的代码’。

JS错误处理:前端JS/Vue/React/Iframe/跨域/Node

js错误的实质,也是发出一个事件,处理他,error实例对象message:错误提示信息,name:错误名称(非标准属性)宿主环境赋予

nodejs提示 cross-device link not permitted, rename 错误解决方法

文件上传的功能时候,调用fs.renameSync方法错误,这个提示是跨区重命名文件出现的权限问题。先从源文件拷贝到另外分区的目标文件,然后再unlink,就可以了。

Js中使用innerHTML的缺点是什么?

如果在JavaScript中使用innerHTML,缺点是:内容随处可见;不能像“追加到innerHTML”一样使用;innerHTML不提供验证,因此我们可能会在文档中插入有效的和破坏性的HTML并将其中断

Web前端开发,必须规避的8个错误点!

现在,有越来越多所谓的“教程”来帮助我们提高网站的易用性。我们收集了一些在Web开发中容易出错和被忽略的小问题,并且提供了参考的解决方案,以便于帮助Web开发者更好的完善网站。

web前端错误监控

为什么要做前端错误监控?1. 为了保证产品的质量2. 有些问题只存在于线上特定的环境3. 后端错误有监控,前端错误没有监控,前端错误分为两类: 即时运行错误和资源加载错误

自定义错误及扩展错误

当我们在进行开发的时候,通常需要属于我们自己的错误类来反映任务中可能出现的特殊情况。对于网络操作错误,我们需要 HttpError,对于数据库操作错误,我们需要 DbError,对于搜索操作错误,我们需要 NotFoundError,等等

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!