Loqate Address Verifier - Detect Zero Credit OnLoad? - javascript

Using the Loqate Address Verification service, is there a way to programatically detect that your account is out of credit, on load of the control? Something like the code below (that I just made up)?
var controlToReturn = new pca.Address(fields, avOptions);
control.listen("load", function () {
if (this.accountCredit == 0) {
//do stuff
}
});
It's possible to handle a zero credit error thrown by the control after you've used it, but at that point you've displayed an address search field, and then have to hide it, and fall back to a standard address form layout (in our case at least).
controlToReturn.listen("error", function (message) {
console.error(message);
const ERROR_MESSAGE_ZERO_CREDIT = "Account out of credit";
if (message != ERROR_MESSAGE_ZERO_CREDIT)
alert("Error with address checker service: " + message);
}
There doesn't seem to be anything in their docs, but I just wondered if anyone knew of any properties on the control / other API calls that would allow this?

The problem is that the Loqate address.js library, which calls their API, is not returning the whole error object, just the message.
This may not be an approach that is endorsed by Loqate, but you can access the original error object through the reference to the pca.Address in the 'error' listener.
You should be able to do this (in the 'error' listener function):
var errorCode = this.error.arguments[1].response.Items[0].Error;
'arguments[1]' is the pca.Request object that caused the error, and 'Items[0]' is the error object, which has the properties 'Error' (the code), 'Description', 'Cause' and 'Resolution'.
Note that 'errorCode' is a string at this point, so you might also want to use parseInt on it.
The full list of error codes is available on the Loqate website. 'Account out of credit' is '3', but there are a number of other errors that you may want to handle differently.

Related

Unable to catch error when fetching data in async function

I'm using npm yahoo-finance to fetch stock data. When I input a stock symbol that doesn't exist, I would like to catch the error.
const yahooFinance = require('yahoo-finance');
async function stockData() {
try {
let data = await yahooFinance.historical({symbol: "SIJGAOWSFA", from: 2020-08-23, to: 2021-08-23});
} catch (error) {
console.error(error)
}
}
stockData();
However it doesn't appear to be a typical fetch error. It's not being caught at all. By that I mean, the error you see below was not logged to the console via the console.error(error). Rather something outside the scope of this file is logging the error. When the error occurs, nothing in catch is executed.
I plan on using this in a for loop, so would like to catch the error so I can avoid executing any following functions.
A collaborator says that:
Is this from an existing project that was working and stopped working, or a new project?
If the former - everything is still working fine on my side. (Very) occasionally there are issues at yahoo that get stuck in their cache, possibly relating to DNS too. I'd suggest to clear your DNS cache and also try querying different data to see if that works.
If the latter (new project), it could be the data you're querying. Try query different data and see if it works. Usually yahoo throws back a specific error if something wrong, but it could be this.
If neither of those approaches work, but you still need to catch this sort of error, given the source code, what it does is:
if (!crumb) {
console.warn('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
And then continues on as normal (without throwing), and eventually returns an empty array.
If you're sure the result should contain at least one item, you can check to see if it's empty, and enter into an error state if it is.
Otherwise, if you don't know whether the array should contain values or not, another option is to overwrite console.warn so that you can detect when that exact string is passed to it.
Another option would be to fork the library so that it (properly) throws an error when not found, instead of continuing on and returning an empty array, making an empty successful result indistinguishable from an errored empty result. Change the
if (!crumb) {
console.warn('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
to
if (!crumb) {
throw new Error('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
and then you'll be able to catch it in your call to .historical.

Google Sheets installable trigger: entire function is within try-catch, but errors still occur

I have an entire function wrapped within a try-catch but still get error notifications.
The catch is supposed to ignore this error because it is benign; i.e. I do not re-throw the error after catching it.
function myOnEdit(event){
try{
//stuff
}catch(e){
if((e.message).indexOf("Must be") != -1){
return;
}else{
//e-mail me the error and display a user-friendly dialogue to the end user
}
}
}
I expect not to be notified of any errors containing the words "Must be." This code is tied to a spreadsheet with data validation, and all the data validation errors are custom set to an error message of "Must be" followed by the required format. For instance, one column lists phone numbers, so the data validation error is, "Must be ###-###-####."
Instead, I receive the automated Google e-mail "Summary of failures" listing errors for these data validations:
Your script, SED Code - PRD, has recently failed to finish successfully. A summary of the failure(s) is shown below. To configure the triggers for this script, or change your setting for receiving future failure notifications, click here.
The script is used by the document SED - PRD.
Summary:
Error Message Count
Must be ###-###-####. 7
Start Function Error Message Trigger End
5/14/19 5:55 AM myOnEdit Must be ###-###-####. edit 5/14/19 5:55 AM
Other people are using this spreadsheet (I barely use it at all -- I'm just the tech guy) and I am unable to reproduce this error. About 70 people use it and they are not tech savvy -- they probably will not tell me they are getting this error, even if I ask them to.
However, the error notification e-mail distracts from potential "real" errors. Hence, I do not just want to turn off error notifications.
These errors are also not listed in Stackdriver Error Reporting, which is confusing. The only reason I know they are happening is because of the e-mail notification.
GoogleScripts (.gs) are not the same as standard js.
In this case you don't need e.message. It should be:
if((e).indexOf("Must be") != -1){
The following test should pass if you use (e).indexOf, but it should fail with (e.message).indexOf:
Create an empty spreadsheet and add the script below
Add 'onMyEdit(B1)' to cell A1
Add 'testfunction(B1)' to cell A2
Type 3 in B2
function onMyEdit(input){
var inputString = ''+input;
if(inputString.indexOf(3)!=-1) {
throw "Must be";
} else {
Logger.log('success', input);
return 0;
}
}
function testfunction(cell) {
try {
onMyEdit(cell);
} catch (e) {
if((e).indexOf("Must be")!==-1) {
return 'failure';
}
}
return 'success';
}

Strange error message being returned when creating calendar event

I'm creating a google calendar event using the Node.js Google Client API, I'm requesting a conference be created with the event using the following object:
var conferenceData =
{
createRequest:
{
requestId: uuid(),
conferenceSolutionKey:
{
type: "hangoutsMeet"
}
}
}
I get an error back from the server saying: Error: Invalid conference type value. Which doesn't make any sense, since, according to this documentation hangoutsMeet is an acceptable value:
The possible values are:
"eventHangout" for Hangouts for consumers (http://hangouts.google.com)
"eventNamedHangout" for classic Hangouts for G Suite users (http://hangouts.google.com)
"hangoutsMeet" for Hangouts Meet (http://meet.google.com)
Anybody have any idea why it could be returning that error?
I am facing the same problem at the moment.
I believe it actually comes from the fact that the calendar where you try to insert the event does not accept the "hangoutsMeet" conference call type.
You can check that by using the API to get the calendar setup details, in conferenceProperties.allowedConferenceSolutionTypes:
- https://developers.google.com/calendar/v3/reference/calendars/get
- https://developers.google.com/calendar/v3/reference/calendars#resource
For my particular case, I can observe that the calendar only supports "eventNamedHangout", and "hangoutsMeet" is not listed.
That being said, I have no idea about how to actually make sure the "hangoutsMeet" type is supported by a specific calendar resource.
Edit
It seems that my problem was coming from the fact I was using a GCP service account - in that case what I observe is that only the eventNamedHangout type is supported.
When sending the very same payload to the API with an access_token obtained via the oauth dance, hangoutsMeet becomes available.
I got this working. As per the events docs you referred to, if providing conferenceSolution then at least one entryPoint must also be provided. Otherwise use createRequest:
"Either conferenceSolution and at least one entryPoint, or createRequest is required."
Does your uuid() return a string ?
and try smth like this instead :
const event = {
"conferenceData": {
"createRequest": {
"requestId": "someRandomKey",
"conferenceSolutionKey": {
"type": "hangoutsMeet"
}
}
}
};

Determine if Google Maps API is using an invalid key during runtime

I'm looking for a way to determine whether a valid Google maps API key is being used. Using an invalid key, we receive an error stating that the google API has been disabled. I'd like to capture that return, and determine whether or not to do our geocoding functions based on that return.
As it stands, when we save a record, we look to see if the address has been changed. If it has, we get the geocode of that address, and after the success/failure message has been passed back, we continue on with our processing before we save the record.
When the API is disabled, the code simply stops. Nothing is returned - no success or failure. At this point, our code stops as well as we rely on the return so we know where to go from there. We are not looking for a way to get around licensing, simply a way to determine whether the API is disabled at runtime. Any ideas?
Well there's something i found in Web > Maps JavaScript API > Events under title "Listening for authentication errors"
If you want to programmatically detect an authentication failure (for
example to automatically send an beacon) you can prepare a callback
function. If the following global function is defined it will be
called when the authentication fails.
so you just need to define a global function:
function gm_authFailure() { /* Code */ };
Unfortunately there is no implemented option to detect a disabled API.
Last year I've made a feature-request , but I don't think that something will happen.
two possible options(there may be more):
when you use a map usually the API first will try to create the map(some elements will be added to the map-container ). When the API will be disabled, these elements will be removed. So you may do something when this happens(e.g. set a variable that indicates the disabled-status):
document.getElementById('map-canvas')//map-container
.addEventListener ('DOMNodeRemoved', function(e){
if(!this.children.length){
alert('the API has been disabled');
if(window.google && window.google.maps){
window.google.maps.disabled=true;
}
}
}, false);
override the alert-method to intercept the particular message:
(function(f){
window.alert=function(s){
if(s.indexOf('Google has disabled use of the Maps API for this application.')
===0){
if(window.google && window.google.maps){
window.google.maps.disabled=true;
alert('the API has been disabled');
return;
}
}
f(s);
}
})(window.alert)
In both cases you may later use the (custom)disabled-property of google.maps to check if the API has been disabled:
if(google.maps.disabled===true){
//execute alternative code
}

How do I catch an invalid API key for google maps

I have this code:
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=babab" type='text/javascript'></script>
If the key is invalid then it pops up an alert, but I want to perform some action in this case. I'm not sure how to hook into it though. Any ideas?
Google does not offer an external method of checking the Google Maps API key. Hence you cannot query some service with e.g. "Is this code valid abcde1234" and get a TRUE/FALSE response.
There is a discussion on how the Maps API key is generated. But I suggest you look at a post from Mike Williams about the GValidateKey function. This is the function actually doing the magic validation - what it exactly does, like creating a hash from your Google account / domain - we don't know.
I see two solutions for your problem of checking whether the API key provided is correct:
Overwrite the incoming alert with some custom code (check for the content of the alert, or check if an alert occurs withing X seconds after page load)
Somehow get the GValidateKey function to validate your key beforehand. Maybe you can call it before referencing the API Javascript? Sounds kind of hackish to me...
The problem you will likely have is that you don't know what Google actually checks. The referrer, the referring site, the host - many possibilities (it is not the IP address of the server, but the name plus some additional information).
I just ran across the need to perform an action if an invalid API key was used. Google's documentation states:
If you want to programmatically detect an authentication failure (for example to automatically send an beacon) you can prepare a callback function. If the following global function is defined it will be called when the authentication fails.
This was all I needed to do:
function gm_authFailure() { // Perform action(s) }
For modern browsers (IE9+ and others) you may use DOMNodeRemoved event. You just need to add event handler to the element that you pass to the map constructor:
var map = new google.maps.Map(element, myOptions);
element.addEventListener("DOMNodeRemoved", function(e){
if (e.target === element){
//your code here
element.removeEventListener("DOMNodeRemoved", mapWasRemovedHandler, true);
}
}, false);

Categories

Resources