簡體   English   中英

可以用 try catch 塊 React 應用程序處理錯誤(狀態代碼 4xx)嗎

[英]Can React app handle error (status code 4xx) with try catch block

我正在學習 React(帶鈎子),但遇到了一個奇怪的問題。 我目前正在研究 Notes 應用程序(來自 FullStackOpen 學習反應)。 我的數據庫只接受內容長度大於 4 個字符的筆記。 如果筆記無效,我的服務器會捕獲 ValidationError 並返回帶有狀態碼 401 的錯誤消息,而不是新筆記。 我的目標是在前端捕獲此錯誤並顯示錯誤消息。

后端代碼:

try{
    const savedNote = await note.save()
    user.notes = user.notes.concat(savedNote._id)
    await user.save()

    response.json(savedNote.toJSON())
  
  } catch(e) { 
    //console.log(e.name)
    const msg = {error: 'too short!!!'}
    //console.log(msg)
    return response.status(401).json(msg)
  }

當我嘗試在應用程序的前端接收數據時出現問題。 我的開發控制台顯示錯誤:無論我做什么,請求都失敗,狀態碼為 401 我找不到進入前面的catch塊的方法。

與服務器通信的前端代碼:

const create = async newObject => {
  const config = { headers: { Authorization: token } }
  const response = await axios.post(baseUrl, newObject, config)
  console.log(response.data)
  return response.data
}

(...)

const addNote = (event) => {
    event.preventDefault()
    try{      
      const noteObject = {
        content: newNote,
        date: new Date().toISOString(),
        important: Math.random() > 0.5
      }

      noteService
        .create(noteObject)
          .then(returnedNote => {
            setNotes(notes.concat(returnedNote))
            setNewNote('')
            setErrorMsg('')
            setUserNotes(userNotes.concat(returnedNote))
      })    
    } catch (e) {///<----how to get there          
      setErrorMsg('note too short! minimum 5 characters')
      setNewNote('')
      setTimeout(() => {
        setErrorMsg(null)
      }, 5000)
    }
  }

一些建議將不勝感激。

解決方案:

鏈接承諾 - .catch()

const addNote = (event) => {
    event.preventDefault()
      const noteObject = {
        content: newNote,
        date: new Date().toISOString(),
        important: Math.random() > 0.5
      }

      noteService
        .create(noteObject)        
        .then(returnedNote => {
            setNotes(notes.concat(returnedNote))
            setNewNote('')
            setErrorMsg('')
            setUserNotes(userNotes.concat(returnedNote))
        })
        .catch(e => {
          setErrorMsg('note too short! minimum 5 characters')
          setNewNote('')
          setTimeout(() => {
          setErrorMsg(null)
          }, 5000)
        })
  }

將 try, catch 塊放在您的 api 調用周圍:

try {
  const response = await axios.post(baseUrl, newObject, config)
} catch (e) {
  // handle error
}

另一方面,我不建議使用401作為無效狀態代碼,因為它具有未授權的保留含義。 請改用400 (錯誤請求)。 狀態碼定義: https://httpstatuses.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM