Why is error undefined in my Axios catch? - javascript

I'm using Vue.JS on the front end, Laravel on the backend, and Axios to post some form data, my axios method is set up like below:
axios
.post("/api/xxxxx", formData)
.then(function(response) {
console.log('inside then');
console.log(response.data);
self.errorMessage = response.data.data.message;
})
.catch(function(error) {
console.log('inside catch');
console.log(error);
self.errorMessage = error.response.data.message;
});
},
Everything works as expected within the 'then' block, but when I clear my cookies and cache and resubmitting, the code in the catch block is triggered however this time no error message is displayed on the front end (using errorMessage).
When I check Vue Dev tools, I can see **Error: Unexpected end of JSON input**.
And in my console: Cannot read property 'data' of undefined
So I guess the error here is showing up as undefined.
What I want is for my errorMessage to contain the message from the response whenever there is an error.
When I check my network tab and preview the response, I do see data.message containing the relevant text: ("Something's gone wrong") But I'm not sure why I can't get this to display when the code in the catch block is triggered.

Related

Returning Error Values Through Axios/Express To React App

I've got a handleSubmit function that fetches data from my backend as part of a larger component. I'd like to send the error information to my redux store and/or local component when the back-end fails, but am unable to do so.
The handleSubmit function looks like this (it's using React hooks, which are wired up correctly. Can post the full component if that is useful):
const handleSubmit = async (e, { dataSource, filter, filterTarget }) => {
e.preventDefault();
setIsLoading(true);
setErrorValue(null);
setError(false);
const token = localStorage.JWT_TOKEN;
const link = filterTarget === "Identifier" ? `http://localhost:8081/api/${dataSource}/${filter}`: `http://localhost:8081/api/${dataSource}?filter=${filter}&filterTarget=${filterTarget}`;
try {
let data = await axios.get(link, { headers: { authorization: token }});
props.setData(data);
setError(false);
setIsLoading(false);
} catch (err){
setErrorValue(err.message);
setError(true);
setIsLoading(false);
};
};
I'm intentionally making bad requests through the form, which will trigger an error in my backend. These are handled through my custom Express middleware function, which looks like this (I'll add more once I get this framework to work):
handleOtherError: (error, req, res, next) => { // Final custom error handler, with no conditions. No need to call next() here.
console.log("This error handler is firing!");
return res.status(500).json({
message: error.message,
type: "ServerError"
});
}
I know that this function is firing because the console.log statement is appearing on my server, and if I change the status code, so does the status code error on the front-end in my Google Chrome console.
In fact, if I go to the network tab, the correct error information appears for my request. Here's the video of me making a bad request:
However, when I try to access the err.message on my front-end, I'm not able to do so. The err.message in my try/catch handler for the handleSubmit function only ever gives me the Request failed with status code XXX
What am I doing wrong?
See https://github.com/axios/axios#handling-errors
You can access the response by using err.response.data.message, not err.message.
Found the answer posted elsewhere: https://github.com/axios/axios/issues/960
Apparently, to get the message, you have to use err.response.data.message
Simply using "err" will only give you a basic string respresentation of the error.

How to show a ERR_NAME_NOT_RESOLVED error to user

My app allows users to specify a server name which is where their installation of our api is. This is so the rest of the app can make calls to that endpoint.
However, I need to display an error message to if we get an error like ERR_NAME_NOT_RESOLVED and it seems that I'm not able to catch this as an error in javascript.
Is there any way around this?
What're you using to make the call to the endpoint? if you're using fetch you don't have an exception, the response is an object with a property error in true and the error messages.
response = {
error: true,
data: { message: 'ERR_NAME_NOT_RESOLVED', code: 404 }
}
If you're using axios, you have to make something like this:
axios.post('/formulas/create', {
name: "",
parts: ""
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});

Fetch still throws despite having catch block

fetch('https://api.postcodes.io/postcodes/aassdd')
.then((resp) => {
console.log(resp.status);
})
.catch((e) => { console.log('ha'); });
For some odd reason the code above will still throw error and execute the .then statement afterwards. Is there a way to fix this ?
Edit: fiddle
Most browser developer consoles normally logs 404 errors by default, and some may, or can be configured to, log all requests.
The fact that you see see an error here doesn't mean a catch-able JavaScript exception was thrown, in addition to JavaScript console logs and throw exceptions, the browser console also shows other things.
There isn't anything you can do in your code to stop this error from appearing in the console, but some consoles would let you hide those requests from the console.
Also, fetch does not throw an error on typical error response codes like 404. This is to make it more-flexible, and let you decide if you still want the content, even if it is a 404 response code.
If you want to throw an error on a non-200 status code, you could do this:
fetch('https://api.postcodes.io/postcodes/aassdd')
.then((resp) => {
if (resp.status !== 200) {
throw new Error('Invalid status code: ' + resp.status);
}
})
.catch((e) => { console.log('ha'); });

How do I get the full error message from my Node and Express server on the client side?

I have an express route that returns a 400 status and an error message. I want to alert the full error message on the client-side, but the alert only says "Object object" when I alert it. I inspected that object and I don't see the full error message that I see logged to my terminal from the server.
On the server the error message says, "djhbf is not defined" because I typed in some random characters to throw an error message. On the client-side, the object has some properties, but none of them contain the error message "djhbf is not defined". The closest thing to an error message is, "status-text: bad request". How do I retrieve the actual error message "djhbf is not defined" on the client-side?
Here is my server.js code which sends the error message in its catch block of a promise:
app.post('/sendEmails', function(req, res, next) {
axios.get(FEED_URL)
.then(data => {
let jobs = data.data.jobs;
fetchClients(jobs, 'email').then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.log(err);
res.status(400).json(err);
})
})
.catch(error => {
console.log(error);
});
});
Here is the client-side code which alerts the error:
sendEmails() {
axios.post("/sendEmails")
.then(res => {
this.setState({
emailsSent: true,
smsSent: false
});
})
.catch((err) => {
console.log(err);
alert(err);
});
}
Updated
This is not an express issue. axios decorates the error object. You just need to change your client side console.log to this: console.log(err.response.data);
You will also need to update your server side logic since you are using axios on both sides. Try res.status(400).json({msg: 'There was a problem with your request'});
If that works you'll just need to drill down in the err object on the server side to see what you want to send back to the client.
See the Error Handling section of the axios docs.

How to handle can-connect errors correcly when connecting to a RESTful API

I've managed to load data and to save data. But cannot understand the error handling scheme needed.
When everything goes fine I receive the same object in that was sent but with an extra attribute _saving (false).
When something goes wrong, for instance try to store a string instead of a number, I'll get:
Bad request (error on the console, don't want that)
The response object (might be usefull to show an error)
"Uncaught (in promise)" error
Example:
Code:
this.save()
.then(function(result) {
console.log('ok1', result);
}).catch(function() {
console.log('errorHandler1');
});
OK:
Error:
I've been trying to use catch on promises, following this guidelines:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
but had no luck at all.
This should should work buy just changing p1.then to thisObjectThatIWantToSave.save.then but it didn't.
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
Again, it still stores the information when the data is correct, the problem I see is that I don't have the tools to decide when was the data correctly stored or not and to avoid triggering errors that can be correctly handled.
I'm using
canjs v3.0.0-pre.11
a restful API provided by feathers
Regarding the error handling ...
Bad request (error on the console, don't want that)
There's no way of preventing the error on the console. This is something chrome does.
The response object (might be usefull to show an error)
You can read the reason for the rejection in can-stache like {{promise.reason}}.
"Uncaught (in promise)" error
I'm not sure why this is being thrown as clearly, your catch is being hit. If you change it to:
this.save()
.then(function(result) {
console.log('ok1', result);
},function() {
console.log('errorHandler1');
});
Do you get the same behavior?

Categories

Resources