Handling errors if no network is available - vue.js

I just implemented my first backend file where I fetch some user data, messages and so on.
Now I wanted to include error handling if there is no network available.
I don´t know if I did it right but this was my approach so far:
import axios from 'axios'
const host = process.env.VUE_APP_URL
export default {
person: async function (currentPerson) {
let params = {
currentPerson: localStorage.getItem("person"),
};
if (user) {
params['currentPerson'] = currentPerson;
}
return axios.get(`${host}/api/currentPerson`, {
params: params
})
//catching network errors
.catch (error => {
if (error.response) {
/*
* The request was made and the server responded with a
4xx/5xx error
*/
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
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
console.log(error)
});
},
In my mounted() function of my main view I fetch the data from my backend file from above:
backend.matches().then(function (response) {
self.contacts = response.data.persons;
});
I tried to check in console if it is working but all I get is the following:
In the catch block I check for
response errors: like 4xx/5xx
request errors: if my network not responding in time
and any other errors
Would this be the right approach to check if a network is available or not? Or does it degrade the user experience when the user checks the error?
My backend file includes more methods.. do I have to write for each method these kind of requests?

In your backend file you don't react whether there is a network connection or not I think.
And only for reference: that is not the backend, but communicates with the backend - the backend is the part of your code what you communicate with, e.g. Laravel code, an API, ...
Try adding the following at the beginning of your catch part:
if (!error.response) {
//network error
console.log('No network connection');
} else if (error.response) {
//the rest of your code
This should print out No network connection in your console.
Run your application, turn off the internet connection and check the console.
These kind of code should always be located in your backend part.

My answer maybe different from your question.
When i create a .net core API with Angular i used three things to check is there network or not?
subscribe to windows's offline/online event
create signalR hub from layout component to API server
API request failed (it means lot of incident, but if 1. or 2. case is true i know what cause 3. case

Related

Axios onUploadProgress jumps at 100% even before the request is done

I have a controller that calls multiple external api from Gmail API concurrently, and then saves the retrieved data into the database, all of this in ONE post request.
To start, I pooled the external api requests, map the results and save it to db.
In my Controller:
$resp = Http::pool(fn (Pool $pool) [
$pool->as('pool-1')->withToken($user->token)->get('https://....call-1');
$pool->as('pool-2')->withToken($user->token)->get('https://....call-2');
$pool->as('pool-3')->withToken($user->token)->get('https://....call-3');
]);
collect($resp)->map(function ($req) {
Email::firstOrCreate(...);
})
In my vue component:
const config = {
onUploadProgress: progressEvent => {
console.log(`sent: ${Math.floor((progressEvent.loaded * 100) / progressEvent.total)}`)
}
}
axios.post(url, param, config).then(response => {}).catch(err => {})
Now, when I check in console.
It should be logging:
sent:0
sent:1
sent:2
...
sent:100
But instead, it automatically logs sent:100 even though the post request is still pending.
Is this a bug in chrome? or axios?, or perhaps it has something to do with external api calls?
Or if it isn't, can someone point out where I went wrong?

How can I fix an Axios interceptor causing property 'status' of undefined error

I have a selection to set permissions for elements to global or private. I'm using the Axios interceptor request to handle looking for the permissions field to have data and, if it does, stringify it. The problem is, it causes me to get a "TypeError: Cannot read property 'status' of undefined" when I attempt to reload the program at all. The only "fix" right now is to log out, remove the interceptor, log in, read it, and then run the check again.
Because of this, I can't even get to the home dashboard of the software. If I clear my cookies, I can go back to the login screen, but no further than that after attempting to log in.
Is there something I'm missing for it? below is the interceptor code. If more information or context is needed, please let me know.
export default {
install: (Vue) => {
Vue.$eventBus = new Vue();
Vue.axios.interceptors.response.use(response => {
return response.data;
}, async error => {
if (error.response.status === 401 && error.config.url != '/api/authentication/login') {
var config = await Vue.$configService.find();
window.location = config.accountPortalUrl;
return
}
console.log(error);
Vue.$eventBus.$emit('notifyUser', 'Uh oh, something went wrong!');
return Promise.reject(error);
});
Vue.axios.interceptors.request.use(
config => {
// check request method -> use post if many params
if (config.data.permissions) {
config.data.permissions = JSON.stringify(config.data.permissions);
}
console.log(config);
return config;
}
);
}
};
Looks like your service API is not responding, this might happen if the user is not authenticated . Your error is at line where you check (error.response.status). Its only possible to get an undefined response when the request was interrupted before response. Most probably if you check your browser network pannel you will see that the preflight check for this request causes a 401 network error. Hence because the preflight failed your actual response comes as undefined. You should sanity check first if your server responded with a response or not and then access the response status.
Something like this might help
if (error.response) {
// Request was made and the server responded successfully
// You can now de-structure the response object to get the status
console.log(error.response.status);
} else if (error.request) {
// request was made but not responded by server
console.log(error.request);
}
So, the answer ultimately was something extremely simple.
if (config.data.permissions)
needed to be
if (config.data && config.data.permissions)

Trying to log in to gmail while using TestCafe

I am learning TestCafe and am trying to create an account on a website and then logging in to Gmail to find the activation link. When I try to do this I just get a browser isn't secure message when I get to the part to enter a password. How do I get Gmail to trust TestCafe?
While you might succeed in doing so, this is not a good approach because:
it's slow doing this via GUI
it's britle because selectors will likely change, and you have no control over Google email selectors, so you won't even know if they change them
A better approach wuld be to use a service like Mailosaur where you can create an account and receive emails that you can later query via an API. Instead of doing a whole e2e flow over GUI, you request an email on Mailosaur's API, and if such an email exists, you'll receive a response you can parse and check for various things.
I've done this in the past, you can see my post here: https://sqa.stackexchange.com/questions/40427/automating-verification-of-sent-email-sms-messages/45721#45721 It's exactly Mailosaur and Testcafe (plus it requires axios as a package), so it seems to be what you're looking for.
To add the same code here:
import config from '../config';
import { customAlphabet } from 'nanoid';
import axios from 'axios';
import Newsletter from '../Objects/newsletter';
async function request (reqObject) {
try {
return await axios(reqObject);
} catch (error) {
console.error(error);
}
}
function serverId () {
return process.env.MAILOSAUR_SERVER_ID;
}
function mailosaurFullEmail (id) {
return (id ? id : nanoid()) + '.' + serverId()
+ '#' + config.mailosaurDomain;
}
fixture `Newsletter`
.page(baseUrl);
test
('Sign Up For Newsletter', async t => {
const id = (customAlphabet('1234567890', 10))();
await t
.typeText(Newsletter.newsEmailInput, mailosaurFullEmail(id))
.click(Newsletter.consent)
.click(Newsletter.sendButton);
let res = await request({
method: 'POST',
url: config.mailosaurUrlEmail + serverId(),
headers: {
'Authorization': 'Basic '
+ Buffer.from(process.env.MAILOSAUR_API_KEY)
.toString('base64'),
'Content-Type': 'application/json'
},
data: {
sentTo: mailosaurFullEmail(id)
}
});
await t
.expect(res.status).eql(200);
});
and it requires some config values:
{
"mailosaurUrlEmail": "https://mailosaur.com/api/messages/await?server=",
"mailosaurDomain": "mailosaur.io"
}
This is definitely much better, but it still has some limitations:
Mailosaur's API can still change, so it won't be exactly without any maintenance
it assumes that an email is sent immediately after a user action (newsletter in my case), but that might be far from reality in many situations such as when emails are sent to a queue where it can easily take several minutes to send an email
If you absolutely have to do it via Gmail, you will still be better off looking at their API that should allow you to search and query email messages as well.
There is an issue related to the Google login. You can try turning on the "Allow less secure apps" Google account setting to workaround this issue. Please note that this setting is available for the disabled 2-Step Verification.

Error when creating a wallet using kin.js

Trying to embed kin.js in an Ionic App, I can see that the key creation using Keypairs and network initialization is ok
const keys = Keypair.random();
const network = KinNetwork.Production;
However when I try to create the wallet
createWallet(network, keys)
.then(res => {
console.log(res);
}, (err) => {
console.log(err)
});
It keeps retrying but at the end it replies with Error: failed to load account:
I can see the API call is made
https://horizon-kin-ecosystem.kininfrastructure.com/accounts/GANWXV7IHG6YGWVIXJNB56OCBIYI7LYKD34CH556YCDOP5LRC2WDJLTC?c=0.32263221858689695
but the response includes this object
{
“type”: “https://stellar.org/horizon-errors/not_found",
“title”: “Resource Missing”,
“status”: 404,
“detail”: “The resource at the url requested was not found. This is usually occurs for one of two reasons: The url requested is not valid, or no data in our database could be found with the parameters provided.”
}
Any missing parameters I should supply beyond the network and keys

400 Bad Request when doing a Parse Unity cloud call to user.logIn in Parse.Cloud.Define

When trying to define a Parse Cloud Code server side function to handle login I get 400 Bad Request when I try to call it. When I look at the Parse logs it records the error "Failed with: ReferenceError: user is not defined". But the user is definitely defined!
Below is the definition of the cloud code for LogIn:
Parse.Cloud.define("LogIn", function(request, response)
{
user.logIn(request.params.username, request.params.password,
{
success: function(user)
{
response.success(
{
"success": "Log in successful."
});
},
error: function(user, error)
{
// We must respond with a success in order to access the
// result of the request inside Unity.
response.success(
{
"error": "Log in failed.",
"code": error.code,
"message": error.message
});
}
});
});
From Unity I make this call to the LogIn coud code function:
ParseCloud.CallFunctionAsync<Dictionary<string, object>> ("LogIn", userInfo).ContinueWith (t =>
{
etc.....
}
I get the following error logged in the server side Parse logs when I call the above from Unity using user sashas123 and also student123:
E2014-09-26T17:06:18.001Z] v8: Ran cloud function LogIn with: Input:
{"username":"sashas123","password":"test"} Failed with:
ReferenceError: user is not defined
at main.js:43:5
E2014-09-26T17:38:50.474Z] v10: Ran cloud function LogIn with:
Input: {"username":"student123","password":"test"} Failed with:
ReferenceError: user is not defined
at main.js:43:5
The following snapshot from the Data Browser shows that the above users are definitely defined:
![Parse User class][1]
Is there any issue with calling user.LogIn on the server side through Cloud Code or is this a Unity issue?
It looks like user.logIn should be request.user.logIn :)
I find it's best to handle the case where the function may be called without a logged in user too:
if (request.user.logIn != null)
{
...
}
else
{
response.error("This function must be called with a logged in user!");
}
Hope this help!