Why Request API when error always goes to catch - javascript

I have some questions about requesting API from the server. I make a function for request API, the example I have a request API login when the user fills the email wrong, response API is "email or password is wrong!", when I try in postman is success the response but when I try in my code the response always from the catch, not from response API. My code for request API like below
const handleSubmitLogin = async (input) => {
try {
const result = await axios.post(`${BASE_URL}/users/client/login`, input);
if (result.status == 200 || result.status === "success" || result.status == 201) {
await setAuthKey(result.data.data.token);
await setLoggedUser(JSON.stringify(result.data.data));
dispatch(setUserLogin());
dispatch(setDataLogin(result.data.data));
} else {
setModalActive({ status: true, data: result.message });
}
} catch (error) {
console.log(error);
setModalActive({ status: true, data: translations["please.try.again"] });
}
};
when a user fills an email or password wrong, the response is always from the catch response not from the API response. Can anyone give suggestions for this case?
Edit:
This is result from when user wrong password

If your API responds with a non-successful status code (>= 400), Axios will reject the promise and your code will go into the catch block.
You can still access the response data via error.response.data. See Axios - Handling Errors
try {
const result = await axios.post(`${BASE_URL}/users/client/login`, input);
// etc...
} catch (err) {
console.warn("login", error.toJSON());
setModalActive({
status: true,
data: error.response?.data?.message ?? translations["please.try.again"],
});
}
It's important to use optional chaining since the error may not have a response or data depending on what exactly failed.

Related

nodejs app crash on openai dall-e 2 api rejected request

I'm surely dumb, but I'm not able to figure out how to handle openai api rejected requests
( for the context, dall-e 2 is an image generator )
when user tries to generate forbidden images, my nodejs app just exits
async function start(arg) {
try{
// generate image
const response = openai.createImage({
prompt: arg,
n: 1,
size: "1024x1024",
});
// on success response
response.then(res =>{
console.log("ok");
})
response.catch(err =>{
console.log(err);
});
} catch(e){
console.log(e);
}
}
it gives me something like that on the exit :
data: {
error: {
code: null,
message: 'Your request was rejected as a result of our safety system. Your prompt may contain text that is not allowed by our safety system.',
param: null,
type: 'invalid_request_error'
}
}
tried using response.catch and try catch without success, the app just exits everytime
I at least want to ignore this error in the first place
in a second hand, I would like to console.log the given message (data.error.message)
I don't know what to do to by honest, don't even understand why try catch isn't working
With the details given, my guess would be that the Promise returned by getImages is being rejected. You could debug this a bit by adding some additional logs into your .catch callback and catch statement.
How to do this really depends on what you're trying to do with this api, the code as it's currently written would log something and exit no matter what happens.
There's a couple ways to handle this
Use your .catch to handle the error. Utilizing promise chainability you can get something like this
openai.createImage({
prompt: arg,
n: 1,
size: "1024x1024",
user: msg.author.id,
})
.catch((e) => {
if (e.data.error.message.includes('safety system')) {
return 'something'
}
console.error(e)
})
If you need the response object, the asnwer might be different. Looks like the openai package is built on axios and you can pass axios options into it. See https://axios-http.com/docs/handling_errors and the Request Options section of https://npmjs.com/package/openai
EDIT
I found my solution thanks to #JacksonChristoffersen
Basically I was getting http status 400
I just added request options from axios to validate http status smaller than 500
Here's the solution:
async function start(arg) {
try{
// generate image
const response = openai.createImage({
prompt: arg,
n: 1,
size: "1024x1024",
},{
validateStatus: function (status) {
return status < 500; // Resolve only if the status code is less than 500
}
});
// on success response
response.then(res =>{
console.log("ok");
})
response.catch(err =>{
console.log(err);
});
} catch(e){
console.log(e);
}
}

Trying to access error response 500 axios

I am not able to access the response of error - 500 in axios
export const dowloadFilePDF = (data) => {
return axios
.request({
method: 'GET',
url: `${basePath + data[0]}`,
responseType: 'blob',
headers: { Authorization: Authorization },
})
.then(response => {
console.log(response)
let fileName = response.headers['content-disposition']?.split(';')[1]?.split('=')[1]?.split('"').join('')
fileName = fileName ? fileName : 'data.pdf'
fileDownload(response.data, fileName)
})
.catch((error) => {
console.log(error.response.data)
})
}
I am not getting the response instead its returning as
data : Blob {size: 215, type: 'application/json'}
According to the documentation, you can't assume error.response will be filled in. Here's the code the documentation shows with the inline comments explaining it:
Handling Errors
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
There's another aspect to this as well: You're calling catch on the promise returned by then, not on the promise returned by axios. If the axios promise is rejected, you'll reach that rejection handler, but you'll also reach it if the axios promise is fulfilled but then your fulfillment handler throws an error (or returns a promise it ultimately rejects). In that latter case, the error probably won't have a response property at all.
the best way to catch errors instead of trying a lot of lines of code in the catch method by promise is using the tools in the Axios names interceptor.
interceptor has two property request and response. In response we can simulate the errors status and based on the status code we can do whatever we want. for example :
axios.interceptors.response.use(null, error => {
console.log("error : " , error);
const expectedError = error.response && error.response.status >= 400 &&
error.response.status < 500;
if (expectedError) {
return Promise.reject(error);
}
alert("unexpected error is happen");
});
if you need more help here is the original link

Vuex axios call can't handle 422 response

I'm trying to handle 422 response from my API in case data is invalid when making an async Axios call.
In a component, I have a method like:
async saveChanges() {
this.isSaving = true;
await this.$store.dispatch('updateSettings', this.formData);
this.isSaving = false;
}
And in my actions like this:
let response;
try {
response = await axios.put('/api/settings', settings);
console.log(response);
} catch (e) {
console.log('error');
console.log(e);
}
If the request is successful, everything works fine, and I get a response. However, if the response status code is 422, it doesn't fail or throw an exception, and the response is empty. I've tried with .then(()).catch(()), but no luck either as I need it to be async.
Any suggestions what I might be doing wrong?
By default, Axios only throws an error for HTTP status codes between 200 and 300.
Either configure Axios to also throw for 422 by setting validateStatus:
axios.put('/api/settings', settings, {
validateStatus: status => status >= 200 && status < 300 || status === 422
})
Or check the status code in your normal callback:
response = await axios.put('/api/settings', settings);
if (response.status === 422) {
// throw error
}

VueJs auth not passing

I'm having some problems with authentication with Vue.
I'm trying to check user data and return him if he is validated or not, I'm catching errors as well, but this is meant in case if some other error happens.
This is my code:
loginJWT ({ commit }, payload) {
return new Promise((resolve, reject) => {
jwt.login(payload.userDetails.email, payload.userDetails.password)
.then(response => {
// If there's user data in response
if (response.data.userData) {
// Navigate User to homepage
router.push(router.currentRoute.query.to || '/')
// Set accessToken
localStorage.setItem('accessToken', response.data.accessToken)
// Update user details
commit('UPDATE_USER_INFO', response.data.userData, {root: true})
// Set bearer token in axios
commit('SET_BEARER', response.data.accessToken)
resolve(response)
console.log(response.data.accessToken);
} else {
reject({message: 'Wrong Email or Password'})
}
})
.catch(error => { reject(error) })
})
}
As you see I have 'Wrong Email or Passoword', but this message never showed.
I tried like if(response.status === 200) and else if(response.status === 400) to catch that status and show the message, but no success anyway. Ofc when I put invalid credentials, it's returning 'Request failed with status code 400', but I want to show 'Wrong Email Or password'.
I even tried to check if first gives response status 400 before even check if there is response.data.userData like:
if(response.status == 400){
reject({message: 'Wrong Email or Password'})
}
But still not a success.
What I really want to return is the message that I'm giving from the response, I could just return the message 'something is wrong' in .catch(error), but I can't catch response.data.message like this, because I have message receiving from my backend.
Any ideas on how to resolve it?

Axios post entering catch block even after successful Rest API call completion

My axios post request is not returning the value returned by the API in a non success 401 scenario. It works fine when its a success scenario.
My reset Password API returns the status code, and a message for every call. when I use post man to test its output for resetting a password, giving incorrect current password, I get
Postman Output:
statusCode: 401,
headers: {
.......
........
},
body: "{"code":"NotAuthorizedException","name":"NotAuthorizedException","message":"Incorrect username or password."}" <--- This is the body output
But in my axios post, it goes to the catch block:
await Axios.post(resetAPIUrl, resetParams, config).then(value=> {
console.log(`Returned data ----> ${JSON.stringify(value)}`);
resolve(value);
}).catch(error=>{
console.log(`Failing--->${error}`)
reject(error)
});
this is the error that I am getting in the catch block of Axios post:
Error: Request failed with status code 401
The error reason is correct. But why isn it going into catch block? Its a successful completion of the process. Calling the API directly from post man gives me the correct output structure.
Interceptor was the answer. Since Axios doesn't consider any response other than 200 as the success scenario, interceptors can be used to capture the other responses:
{
Axios.interceptors.request.use(req=>{
console.log(`This is the request ---> ${req.method} ${req.url}`)
return req;
})
Axios.interceptors.response.use(res => {
console.log(`res status ---> ${res.status}`)
resolve(res)
return res;
}, (error)=>{
console.log(`This is the error status ---> ${error.response.status}`)
if(error.response.status === 401){
resolve(error.response);
}
})
await Axios.post(resetAPIUrl, resetParams, config);

Categories

Resources