【问题标题】:Calling async function within another fails, yet code execution continues, no error caught in try catch在另一个中调用异步函数失败,但代码继续执行,在 try catch 中没有发现错误
【发布时间】:2021-02-12 17:30:16
【问题描述】:

我很困惑。我有一个异步函数,我在其中调用另一个函数,当失败时,错误出现在浏览器控制台中,但主函数继续。

下面这个函数失败了,我在浏览器控制台日志中看到错误:

async function create (newContact)  {
    try {
        const request =  await axios.post(baseUrl, newContact);
        return request.data;
    } catch (error) {
        console.log(`Failed to create contact. Error: ${error}`)
    }
}
  

我在下面的另一个函数中调用该函数。发布请求肯定会得到 400 响应错误,但下面此函数中的代码继续没有错误(参见 Else 语句)。为什么?

async function addPerson (event) {
    try {
      event.preventDefault();
      const newPerson = {
        name : newName,
        number: newNumber
      }
      const person = searchPeople(newName);
      if (person !== -1) {
        if (window.confirm(`${newName} is already added to phonebook, replace the old number with a new one?`)) {
          const updatedContact = await contactsService.update(persons[person].id, newPerson);
          setPersons(persons.concat(updatedContact));
          setMessage({text: `Updated ${newName}`, type: 'notification'}) 
        }
      } else {
        const newContact = await contactsService.create(newPerson);
        // console.log("NEW: ", newContact);
        setPersons(persons.concat(newContact));
        setMessage({text: `Added ${newName}`, type: 'notification'}) 
      }
      setNewName('')
      setNewNumber('')
    } catch (error) {
      setMessage({text: `Error: ${error}`, type: 'error'}) 
    }
  }

浏览器输出:

Failed to create contact. Error: Error: Request failed with status code 400 contacts.js:18:16
NEW:  undefined

尽管 create() 失败,但前端显示成功消息,因为代码执行没有停止。

【问题讨论】:

  • 两个问题,1.searchPeople()是同步的,2.你说的错误是什么?
  • @JeremyThille searchPeople() 只是一个地图功能。 create() 中的错误被捕获,但在 addPerson() 中没有被捕获。
  • 如果searchPeople().map() 函数,为什么它会返回-1? map 返回一个数组,而不是一个数字
  • const searchPeople = (name) => { return persons.map(person => person.name).indexOf(name); }
  • 我对 searchPeople 没有意见。

标签: javascript async-await try-catch


【解决方案1】:

create() 调用不会失败。您捕获并记录了错误,然后返回undefinedaddPerson 的执行不受影响 - 没有抛出异常需要处理。

因此,如果您无法处理错误,请不要捕获它

async function create (newContact)  {
    const request =  await axios.post(baseUrl, newContact);
    return request.data;
}

或重新抛出异常

async function create (newContact)  {
    try {
        const request =  await axios.post(baseUrl, newContact);
        return request.data;
    } catch (error) {
        throw new Error(`Failed to create contact. Error: ${error}`);
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2012-06-04
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多