I'm developing an application with Next.Js with a separate back end, I'm having a problem handling the error returned by my API in Next when I try to make the authentication. I'm using Axios to make requests.
When I send an incorrect credential (username or password) my API sends a response like this
res.status(400).json({error: "Username or password is invalid!"})
But when I get the error response in the frontend ( Next.Js ) and try to display this message returned in a sweetalert2 alert or in console.log()
, only the error code appears, I can't catch this message from error returned
Below is the error message I catch:
Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
And here the code of the function where I make the request and handle it:
async function signIn({ user, pass }: ILoginRequest) {
try {
const result = await api.post('/login', { user, password: pass });
setUser({
email: result.data.user_info.email,
ra: result.data.user_info.ra,
name_user: result.data.user_info.name_user,
})
setCookie(undefined, 'app-token', result.data.token, {
expires: new Date(result.data.expiresIn)
})
Router.push('./home');
} catch (err) {
console.log(err)
Swal.fire({
title: 'Error!',
text: err,
icon: 'error',
confirmButtonText: 'Aceitar'
})
}
}