简体   繁体   English

如何捕获异步函数中的 javascript 错误

[英]How to catch javascript errors in async functions

How do I catch simple js errors in async functions?如何在异步函数中捕获简单的 js 错误? In the following code the function "errorfkt" is not available.在以下代码中,函数“errorfkt”不可用。 If I remove the "async" keyword in front of the function "testfkt" I see the reference error in the console.如果我删除函数“testfkt”前面的“async”关键字,我会在控制台中看到引用错误。 With the "async" keyword no error is visible.使用“async”关键字看不到错误。

document.querySelector('#btnTest').addEventListener('click', testfkt)

async function testfkt() {
  errorfkt();
  console.log('test');
}

https://codepen.io/Jochen99/pen/NWrEWgb?editors=1111 https://codepen.io/Jochen99/pen/NWrEWgb?editors=1111

During development I often see very obvious errors in async functions because the browser does not complain.在开发过程中,我经常在异步函数中看到非常明显的错误,因为浏览器不会抱怨。 Is there a way to handle this?有没有办法处理这个问题?

Greetings, Jochen问候,乔臣

Exceptions in Promises are available in catch methods. Promise 中的异常在catch方法中可用。

addEventListener('click', (event) => {
    testfkt(event).catch(error => {
        console.log(error);
    });
})

You can also use try/catch with async / await syntax:您还可以将try/catchasync / await语法一起使用:

addEventListener('click', async (event) => {
    try {
        await testfkt(event)
    } catch(error) {
        console.log(error);
    }
})

You can use a try catch block in the function您可以在函数中使用 try catch 块

async function testfkt() {
  try {
    await errorfkt();
    console.log('test');
  } catch(e) {
    console.log(e);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM