I'm learning React (with hooks) and I encountered a weird issue. Im currently working on Notes Application (from FullStackOpen learn react). My database only accepts notes which content length is greater than 4 characters. In case of invalid note my server catches a ValidationError and returns an error message with status code 401 instead of new note. My goal is to catch this error in frontend and display an error message.
Backend code:
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)
}
Problem appears when I try to receive data at the front side of application. My development console displays Error: Request failed with status code 401 no matter what I do. I can't find a way to enter catch block at front.
Frontend code for communication with server:
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)
}
}
Some advices would be appreciated.
Chaining promises - .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)
})
}
Put the try, catch block around your api call:
try {
const response = await axios.post(baseUrl, newObject, config)
} catch (e) {
// handle error
}
On another note, I don't recommend using 401 as the invalid status code as that has a reserved meaning of Unauthorized. Use 400 (Bad request) instead. The definitions of status codes: https://httpstatuses.com/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.