Node.js 错误和异常

错误处理是所有应用程序的重要组成部分。要抛出异常,请使用JavaScript的throw 关键字。在JavaScript中,通常使用 Error 对象和消息来表示错误。你抛出这个错误,以表示错误情况:

  1. <p>The code above generates the following result.</p>
  2. function a() {
  3. throw new Error("Something bad happened!");
  4. }
  5. a();

错误抛出结果

捕获异常

你可以使用try/catch块捕获异常,如在其他语言中看到的:

  1. function a () {
  2. throw new Error("Something bad happened!");
  3. }
  4. try {
  5. a();
  6. } catch (e) {
  7. console.log("I caught an error: " + e.message);
  8. }
  9. console.log("program is still running");

这个程序的输出是:

I caught an error: Something bad happened! program is still running

finally关键字

为了捕获异常,你可以使用catch关键字。对于要运行的代码,无论是否捕获到异常,都可以使用finally关键字。下面的代码显示了一个简单的例子来演示这个。

  1. try {
  2. console.log("About to throw an error");
  3. throw new Error("Error thrown");
  4. } catch (e) {
  5. console.log("I will only execute if an error is thrown");
  6. console.log("Error caught: ", e.message);
  7. } finally {
  8. console.log("I will execute irrespective of an error thrown");
  9. }

catch部分只有在抛出错误时才执行。finally部分仍然执行,尽管在try部分中抛出了任何错误。

注意

这种异常处理方法非常适用于同步JavaScript。对于异步JavaScript,我们应该处理回调中的错误。

  1. setTimeout(function () {
  2. try {
  3. console.log("About to throw an error");
  4. throw new Error("Error thrown");
  5. } catch (e) {
  6. console.log("Error caught!");
  7. }
  8. }, 1000);

对于上面的代码,我们不能告诉代码外面的错误。考虑一个简单的getConnection函数回调我们需要在成功连接后调用。

  1. function getConnection(callback) {
  2. var connection;
  3. try {
  4. throw new Error("connection failed");
  5. // Notify callback that connection succeeded?
  6. } catch (error) {
  7. // Notify callback about error?
  8. }
  9. }

我们需要通知回调关于成功和失败。这就是为什么Node.js有一个约定,如果有错误,调用回调的第一个参数的错误。如果没有错误,我们回调错误设置为null。Node.js的getConnection函数将类似于下面的内容。

  1. function getConnection(callback) {
  2. var connection;
  3. try {
  4. // Lets assume that the connection failed
  5. throw new Error("connection failed");
  6. // Notify callback that connection succeeded?
  7. callback(null, connection);
  8. } catch (error) {
  9. // Notify callback about error?
  10. callback(error, null);
  11. }
  12. }
  13. // Usage
  14. getConnection(function (error, connection) {
  15. if (error) {
  16. console.log("Error:", error.message);
  17. } else {
  18. console.log("Connection succeeded:", connection);
  19. }
  20. });

将错误作为第一个参数确保错误检查的一致性。这是所有具有错误条件的Node.js函数遵循的约定。