I'm trying to do a post in a localhost SQL DB with react/nodejs. Fortunately it does POST and the information goes to the DB. I wanted to put an alert() inside the .then() if it was sucessfull and another alert() inside the catch() if there was a error. The problem is that it gives both 'success' alert and 'error' alert when posting, although it posts all good in the database. Am I missing something?
const submitForm = () => {
Axios.post('http://localhost:3001/api/insert',{
manager:manager,
decisionDate:decisionDate.toLocaleDateString(),
}).then(alert('Success'))
.catch(alert('Failure'))
}
Your syntax is incorrect for the then callback, which results in an error that is then caught by catch. Update the callback to be the following:
const submitForm = () => {
Axios.post('http://localhost:3001/api/insert',{
manager:manager,
decisionDate:decisionDate.toLocaleDateString(),
}).then(() => alert('Success'))
.catch(() => alert('Failure'))
}
Your syntax is not right which results in an error that is then caught by catch clause.
Update the callback to be the following:
axios.post('http://localhost:3001/api/insert', {
manager:manager,
decisionDate:decisionDate.toLocaleDateString(),
}).then(function (response) {
console.log('Success', response);
}).catch(function (error) {
console.log(error);
});
Please refer to axios documentation
Related
I'm making an API request using the async/await pattern in a try/catch block..
async myRequest(data) {
try {
await api.post('/my-endpoint/', data).then((response) => {
console.log(response.data)
});
} catch (ex) {
// WANT TO READ RESPONSE DATA HERE
}
}
If the request succeeds without errors, I am able to read the response with the .then() method.
If the request fails, this API returns a 422 code that triggers the try/catch exception.
However, if the request fails, this API still returns some data in the response body that I would like to to read but unable to because catch is triggered and .then() is never run.
How can I get the response body from the async function within the catch block?
Try this if you are on Axios lib:
catch (e) {
console.log(e.response.data);
}
console.log uses the toString method to format Error objects so it is hard to find the response property if you only log e (error).
Docs: https://axios-http.com/docs/handling_errors
The error object is stored in ex so you can log the error with
} catch (ex) { console.log(ex) }
One of the problems you are making is putting the .then after you call your API. When you are using the try-catch block you don't need to do the then because you can save the result into a variable.
One of the benefits of the try-catch block is that the errors are handled and you can do multiple async calls
async myRequest(data) {
try {
const response = await api.post('/my-endpoint/', data)
console.log(response.data)
} catch (ex) {
console.log(ex)
}
}
If you want to retrieve the response data from a catch block, you can do it technically.
See the following code.
const myRequest = async () => {
try {
const data = await fetch('https://jsonplaceholder.typicode.com/xxx/1').then((result)=> {
// You can change the status code to 422
if (result.status === 404) {
throw new Error('You can put your data here.')
// Make sure the argument you passed in Error is a string
}
return result.json()
})
} catch(e){
console.log(e.message);
}
}
myRequest()
How do I retrieve message from server after calling:
await axios.post(url, data)
export const postData = async data => {
try {
let url = `${api}auth/register`;
let res = await axios.post(url, data).catch(e => console.log(e));
return res;
} catch (error) {
console.log(error);
Alert.alert("Error");
}
};
Now this function is returning undefined in console. My motive is to get the message and code from server response
Try the following
axios.post('url')
.catch(function (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.message);
}
});
I've got the answers. 🙂
So whenever we call axios.post it gives us a .catch() function to use. If the server returns a bad status codes like 500 or 400. The control goes in .catch() and do whatever it says to. Since the control is in .catch() the function postData() does not return anything and remains undefined. Now, to retrieve the messages from the server this is what can we do.
.catch(e => console.log(e.response.data.message))
I'm trying to write a test in jest but keep getting UnhandledPromiseRejectionWarning when I try to use mockRejectedValue
The code looks like this:
it('Should set error message when call fails', async () => {
const context = mockActionsContext();
const user = {
username: 'alice',
password: 'password'
};
const getError = new Error('network error');
(AuthService.login as jest.Mock) = jest.fn().mockRejectedValue(getError);
await actions[ActionTypes.USER_LOGIN](context, user);
// Check is the commits are called
expect((context.commit as any).mock.calls).toEqual([
[MutationTypes.USER_LOGIN],
[MutationTypes.USER_LOGIN_ERROR, 'Oops, something went wrong. Try again later!']
]);
// Login service is called with user login
expect(AuthService.login as jest.Mock).toHaveBeenCalledWith(user);
});
The AuthService.login returns an axios.post which I try to overwrite with a mock.
actions[ActionTypes.USER_LOGIN](context, user) calls the Authservice.login
The test is passing but I don't want any unhandled promise rejection. Anybody an idea how to fix it?
Edit
#goodmorningasif thanks for your reply.
I've been looking at it too long I thing :)
The action looks as following:
[ActionTypes.USER_LOGIN]: ({ commit }: Context, payload: User) => {
return new Promise((resolve, reject) => {
commit(MutationTypes.USER_LOGIN);
AuthService.login(payload)
.then((token) => {
commit(MutationTypes.USER_LOGIN_SUCCESS, token);
localStorage.setItem('user-token', token);
client.defaults.headers.common.Authorization = `Bearer ${token}`;
resolve(token);
})
.catch((error) => {
let errorMessage = 'Oops, something went wrong. Try again later!';
if (error?.response?.status === 401) {
errorMessage = 'Unknown username and password combination!';
}
localStorage.removeItem('user-token');
commit(MutationTypes.USER_LOGIN_ERROR, errorMessage);
reject(error);
});
});
},
SOLUTION
In my case the action is returning a promise witch would get rejected. In the test, I'm calling the action directly and not catching the rejection.
await actions[ActionTypes.USER_LOGIN](context, user).catch(() => null);
This fixed it.
Can we see the actions and reducer code? It's possible that there's an error in your error :)
You're testing that the login function is called and the action returns the error message you set but you're making an assumption about what causes the error. Maybe it's not because of the mockRejectedValue/'network error'.
I'd suggest including the actual error message in the action payload as well as your error message: one is for developers and debugging and one is for the user to know what to do next.
I also found this helpful on understanding UnhandledPromiseRejectionWarning: https://thecodebarbarian.com/unhandled-promise-rejections-in-node.js.html
Good instinct to figure out the issue and not be content with the test passing, by the way!
I am using Node.js and have a database call being performed with a promise. I setup a '.then/.catch' to handle the result of the promise. That part all seems to work without any issue. After I do some processing of the data returned from the database I am attempting to 'redirect' to another route within the '.then' statement. This re-direction seems to be causing a problem with the '.catch' statement. I have no error issues if I remove the 'res.redirect'...is there a workaround? Any suggestions appreciated.
code:
const db = require('./routes/queries');
//**Query PostGres database...
db.getMembers()
.then(function(value) {
console.log('Async success!', value);
//do some processing on the data returned from the promise call here...
//if I insert a redirect here...such as "res.redirect('/_members');"...
//I get a "Caught an error! ReferenceError: res is not defined" message...?
//evidently the redirect fires the '.catch' statement below...why?
})
.catch(function(err) {
console.log('Caught an error!', err);
});
I recommend providing a reusable promise in case you need to find your members list elsewhere in your Express app
const db = require('./routes/queries');
const findMembers = () => {
return db.getMembers()
.then(members => {
return members
})
.catch(err => {
console.log('Caught an error!', err);
});
}
//inside your express app
app.get("/some_route", (req, res) => {
return findMembers()
.then(members => {
//do something with your members list
res.redirect("/redirect_route")
})
})
Okay, this is a pretty simple question.
I am returning a 400 status error along side a message "Index should have 6 digits" message back in my response.
I am using React for my front-end. When I log the body of the response using the fetch api [console.log(response.json())], I can see that I receive it properly.
But for some reason I cannot access it any any way.
Also, I don't know why the status statusText field in the response is empty.
What am I doing wrong?
What is the defacto standard for exception handling from server side?
Thank you.
Edit - code:
errorHandler = (response) => {
if (!response.ok){
console.log(response.json());
throw Error(response.statusMessage);
}
else {
return response;
}
};
addStudent = (student) => {
createStudent(student)
.then(this.errorHandler)
.then((response) => {
console.log('new student status: ', response.status);
this.loadData();
})
.catch((error) => {
console.log(error);
});
};
You'll see that your're getting a Promise object back in your console, this means that your request simply hasn't fulfilled yet.
Chain onto the promise with .then(response => { // handle the response here })
The code should look similar to this:
fetch('/endpoint').then(response => {
console.log(response)
}
Hope this helps!
What I do is what Mike wrote above.
fetch("endpoint")
.then((response) => response.json())
.then((data) => console.log(data.message));