I´m trying to display a error message that i´m throwing in the backend in case a user is already registred, but i´m not getting the result i wanted.
Backend code:
module.exports.register = asyncHandler(async (req, res) => {
const { fullname, email, password } = req.body;
let user = await User.findOne({ email: email });
if (user) throw new Error("Email e/ou senha inválidos!");
user = await User.create({ fullname, email, password });
if (user) {
res.json({
_id: user._id,
name: user.fullname,
email: user.email,
token: tokenGenereator(user._id),
});
} else {
throw new Error("algo deu errado");
}
frontend code:
export const register = ({ fullname, email, password }) => {
return async (dispatch) => {
try {
const config = {
headers: {
"Content-type": "application/json",
},
};
const data = await axios.post(
"http://localhost:5000/api/register",
{
fullname,
email,
password,
},
config
);
dispatch(
uiActions.showNotificatoin({
variant: "success",
message: "Usuário cadastrado com sucesso!",
})
);
localStorage.setItem("userInfo", JSON.stringify(data));
} catch (error) {
console.log(error.response.data.error)
}
};
};
This is the result i´m getting on the console.
What do i have to do so i can display the message i threw?
CodePudding user response:
You must be throwing error without any catch layer outside it. You might want to do something like this
if (user)
return res.status(409).json({ message: "Email e/ou senha inválidos!" });
In frontend you need to catch the error and use the error like this
if (error.response && error.response.data.message) {
// custom message you sent from backend
console.log(error.response.data.message);
} else {
// generic error message
console.log(error.message);
}
It will work in your case. But ideally for large project error should be thrown from controller repo and that must be catched by outer layer and that in response will be do the above work.
CodePudding user response:
HTTP response codes are used to throw error from backend to frontend HTTP response status codes indicate whether a specific HTTP request has been successfully completed or Not. Read More about HTTP response codes. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
200
status code indicates OK status.409
status code indicates Conflict Status.
Backend Code :
if (!user) { // by deafult ok status
res.json({
_id: user._id,
name: user.fullname,
email: user.email,
token: tokenGenereator(user._id),
});
} else { // in case of user found
res.status(409).json("algo deu errado");
}
Frontend Code :
export const register = ({ fullname, email, password }) => {
return async (dispatch) => {
try {
const config = {
headers: {
"Content-type": "application/json",
},
};
const data = await axios.post(
"http://localhost:5000/api/register",
{
fullname,
email,
password,
},
config
);
dispatch(
uiActions.showNotificatoin({
variant: "success",
message: "Usuário cadastrado com sucesso!",
})
);
localStorage.setItem("userInfo", JSON.stringify(data));
} catch (error) {
if (error.response && error.response.data.message===409) {
alert('user already exist');
} else {
console.log('No Internet Connection');
}
}
};
};