Please allow me to ask a possibly easy question. Can someone tell me where the message property of argument err in catch function at the end of fetch API came from? For example in the code snippet below
fetch('exmaple.json')
.then(response => response.json())
.then(json => randomlyMadeFunction())
.catch(err => console.log('Fetch problem: ' + err.message));
I know fetch returns a Promise, and at the end catch function takes rejected reason as parameter, in this case err. I search many articles on MDN js reference, but I couldn't figure out where the property message of err came from. Any explanation or hint would be much appreciated.
Thanks in advance.
If an error occurs during fetch, either a AbortError or a TypeError will be passed to the catch callback, see fetch Exceptions:
AbortError The request was aborted due to a call to the AbortController method abort() method.
TypeError The specified URL string includes user credentials. This information should instead be provided using an Authorization
header.
TypeErrors are Errors and therefore have a message property, see Error.prototype.message.
Related
When using an api I often find myself with a rather complicated error object.
Depending on the API that I am using the error texts are quite helpful and I would actually sometimes like to display them directly to the user. The problem, of course, is that the error objects can look quite differently so it would be very verbose to go through them and pick individual objects in case they exists (dependant on the status code of the error).
Is this just the nature of the error object or is there a better way to do this?
What I do to handle API calls that end up with error is this:
try {
const response = await axios.post("Your URL");
// Your code to handle the result
} catch (error) {
console.log(error.response.data.error)
// Code to display the error to the user
}
error.response.data.error is the actual error message sent from the server, not the error code
I want to bullet-proof some code which takes user input and attempts to fetch data from a URL.
I have something like the following:
fetch(url)
.then(response=>{
console.log(response.ok);
response.text();
})
.catch(error=>console.log(error));
There’s more afterwards in the actual code.
If I enter something like http://rubbish I catch a TypeError which I can handle. If I enter something like rubbish (without the http:// protocol), I get an error like :
GET file:///…/rubbish net::ERR_FILE_NOT_FOUND
and then get my TypeError. The actual error occurs on the first line of the code above, before the catch() block.
What is the correct way to handle an error like this?
I’m doing this in an Electron App, so one thing I don’t have to worry about is browser compatibility.
You could potentially execute different logic in the catch block depending on the type of error. For example:
fetch(url)
.then(response=>{
console.log(response.ok);
response.text();
})
.catch(
if (err instanceof TypeError) {
// Handle this normally
} else {
// Execute other logic depending on the type of error you are receiving
}
);
Hope this helps, good luck :)
everyone!
I got a problem: I'm trying to validate registration form. Totally, it works ok, but I need to validate form via server. In my case, for example, I need to figure out if email is already taken.
I tried to fetch and async/await syntax, but problem is still the same:
DOMException: "The operation was aborted. "
The way I understand it right now is readableStream (what actual response body is) is locked. So the wrong error is thrown, and I cannot get server response.
try {
const response = await fetch(options.url, options.requestOptions);
const body = await response.json();
if (options.modifyDataCallback instanceof Function) {
body.data = options.modifyDataCallback(body.data);
}
return body.data;
} catch (error) {
throw error;
}
How do I see the solution? I send request and recieve some server error like
code: email_in_use
message: Email '...' is already in use.
Then I need to throw error and catch it in other place in order to show corresponding error message to client.
In browsers network tab I do receive what I want to receive, but can't get the same JSON-response in my code.
Google chrome provided more information: net::ERR_HTTP2_PROTOCOL_ERROR 200.
And the problem was on backend. It is written in C# and API method returned Task. The problem was solved by adding async/await for this method.
I have a function which use axios get method and on the promised returned I have added error handling to handle a situation when service I am trying to connect to has been disabled.
axios.get('/someurl')
.then(() => {
// this does not matter
})
.catch((err) => {
logger.error(TAG, 'postCreateVm', err);
return reply(Boom.forbidden(err.message));
});
When I use curl I can see the message, status of response is 403:
# curl -X GET localhost:3000/someurl
{
"message": "abort"
}
The problem is that when I try to access 'message' property i get nothing, but I know it's there! (I have tried to use err.response.data as well with no success also)
According to the documentation I should be able to access it: axios handling errors
What is the proper way to access this message?
I've looked at his code, and it appears the correct response is in the error, but in axios, settle.js masks it with a generic response. You can see the server response by logging the error object in your catch block as stringified JSON:
console.log('caught:::', JSON.stringify(response, null, 2))
So in my case, I fixed it by accessing the returned error as:
error.response.data.message
My catch function received the response property instead of error object. So, to access message I had use:
err.data.message
The new js fetch API fails the promise if the request fails (400):
fetch(uri).catch(function(err) {
console.log(err);
});
Is there really no way to get the response body when this happens? e.g. to check an error code.
EDIT: I've created a js fiddle: https://jsfiddle.net/4x4xLwqo/ that calls this mockbin endpoint: http://mockbin.org/bin/d87acbb0-526e-4d66-aea4-b827d9c35031/view
EDIT 2: updated jsfiddle to use a better endpoint: https://jsfiddle.net/4x4xLwqo/2/
fetch won't go into catch if it encounters a HTTP error. You can handle that with a regular then.
From MDN:
A fetch() promise will reject with a TypeError when a network error is encountered, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true.
And an accompanying example, from MDN as well:
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
} else {
console.log('Network response was not ok.');
}
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});