5 种JavaScript 中的高级异常处理方法

123 阅读1分钟

1.自定义异常

JavaScript 允许开发人员通过从内置错误对象创建新对象来定义他们的自定义异常。这允许开发人员向最终用户提供更具体和信息更丰富的错误消息。


function CustomException(message) {
   this.message = message;
   this.name = "CustomException";
}

CustomException.prototype = new Error();
CustomException.prototype.constructor = CustomException;

throw new CustomException("This is a custom exception message.");

在此示例中,我们创建了一个新对象 CustomException,它扩展了内置的 Error 对象。当我们抛出 CustomException 时,它将包含我们定义的自定义消息。

try-catch-finally


try {
   // Code that may throw an exception
}
catch (exception) {
   // Code that handles the exception
}
finally {
   // Code that always executes
}

Promises


new Promise((resolve, reject) => {
   // Asynchronous code that may throw an exception
}).catch((exception) => {
   // Code that handles the exception
});

Async/await


async function example() {
   try {
      // Asynchronous code that may throw an exception
   }
   catch (exception) {
      // Code that handles the exception
   }
}

window.onerror


window.onerror = function (message, url, line, column, error) {
   // Code that handles the uncaught exception
};