How to show a ERR_NAME_NOT_RESOLVED error to user - javascript

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)
});

Related

Why is error undefined in my Axios catch?

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.

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.

Axios GET route 404-ing, Node.js/Express

I have the following simple GET inside a function.
axios
.get(`/api/search/q=${this.value}`)
.then(res => {
console.log(res.data);
});
The GET 404's if I enter a query (the letter 'a' in this case):
GET http://localhost:7777/api/search/q=a 404 (Not Found)
so, of course I get an Uncaught promise error from the .then:
Uncaught (in promise) Error: Request failed with status code 404
I figured that it must be a simple routing problem, but my express route is:
router.get('/api/search', someController.someFunction)
The function in the controller works (ie responds with the data) as I have used it elsewhere in the app, so I feel that I have narrowed it down to the axios GET not finding the api. But I can't figure out why, as the path looks OK to me.
You were 404 getting because node is expecting only /api/search but your trying /api/search/:q which is different altogether, try
axios.get('/api/search/', {
params: {
q: value
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
since any number of parameters added will not make the URL clumsy, an alternate for
axios.get('/api/search?q=${this.value}').
and on the server
router.get('/api/search', someController.someFunction)
and in your controller
if(req.query.hasOwnProperty('q')){
var q = req.query.q;
}

Apollo Client: retrieving the results from a query with errors

I'm using the GraphQL Apollo Client. And I'm trying to retrieve the results from a query with errors.
GraphQL response
How do I retrieve the data, even when an error is returned in the same response?
This automatically catches the error. Instead, I want it to access the data.
this.client.query({
query: gql(query),
variables: variables
}).then(function ({ data }) {
return data;
}).catch(error => console.log(error));
Couldn't find anything in Apollo docs about this. Any ideas?
if you stumble here in future
In Apollo-client there are various error types as follow:
1. GraphQL Errors,
2. Server Errors,
3. Transaction Errors,
4. UI Errors,
5. Apollo Client Errors.
As # Alexander Schoonderwaldt you can learn about this errors and error policy here
You can handle/catch graphql errors using code below. If the values returns undefined, its no longer a graphql error. You need to investigate. You may have network error that returns Error CONNREFUSED or others.
.query({
query: myquery
})
.then(({ data }) => {
console.log(data.user);
return { loggedInUser: data };
})
.catch(errors => {
// Fail gracefully
console.log(errors.message); // log grapgql error
return { loggedInUser: {} };
});

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.

Categories

Resources