繁体   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