error handling for server errors with Google Apps Script - google-apps-script

I'm building a WebApp that creates a Google Document from a template and contains some user supplied data as well as data fetched from a 3rd party service. Since all of the Class (DriveApp, DocumentApp, etc) methods make a request to the Google server, a server glitch could cause a simple statement like var doc = DocumentApp.openById(DOC_ID); to fail, throw an error and stop the entire process dead in its tracks... without the user having any idea why everything appears to be "frozen" (unless he is savvy enough to check the console).
For that reason, would it be appropriate to wrap any/all functions using those methods in a try/catch? Something like:
function createDoc(DOC_ID) {
try {
var doc = DocumentApp.openById(DOC_ID);
DriveApp.someMethod(...);
doc.someOtherDocumentMethod();
...
} catch(e) {
handleServerError(e);
return false;
}
return doc;
}
or is there a better way to handle any errors that may be out of the developer's control?
EDIT
Here's the request I send from my HTML page...
$('form').submit(function(e) {
e.preventDefault();
var obj = $('form').serializeObject();
var gurl = 'https://script.google.com/macros/s/AKfycbzmhaub3ojPARA-B-Y2uVC2BJZPaRvbgMwMTH9pd7R9aHuAD5M/exec';
$.ajax({
url: gurl,
type : "GET",
data: obj,
dataType: 'jsonp',
success : function (data, status, xhr) {
console.log("success");
console.log(data);
},
complete : function (xhr, status) {
console.log("complete");
}
});
});

Related

AJAX HTTP-POST-Request - Saving JSON responses

I want to make a HTTP-POST-Request with AJAX to call a JSON API. So, the API should return a response in JSON. I can see on the console of the API, that the request is successful. But the problem is, that no data or status is returned, or that I can't use it with JQuery. Here is my function:
$.post("http://api-adress/controller",
{
email: input_mail,
password: input_pw
},
function(data, status){
alert(data);
alert(status);
}, 'json');
I guess the problem is that the response from the Server does not get saved in the variables data and status correctly.
I would suggest to change a little bit your code like below:
var dataString = {
email: input_mail,
password: input_pw
}
$.post("http://api-adress/controller", dataString, function (result) {
})
.done(function (result) {
//Here is your result. You must parseJSON if it is json format
var data = jQuery.parseJSON(result);
})
.fail(function () {
//use this if you need it
})
Also make sure that you get the response through firebug in console tab. You can check there what you post, what you get etc.

Ajax call to JsonResult in Controller fails with 404 error, "resource not found"

Here is my ajax code in my "ManageUserRoles.cshtml":
//HIT THE DATABASE FOR USERNAME GIVING IT THIS USERNAME
function isUserValid(thisUser) {
$.ajax({
url: "/Roles/isUserValid/" + thisUser,
type: 'POST',
success: handleResultResponseUserName,
error: function (xhr) { alert("Error..."); }
});
}
//handles data back from ajax call
//RESET INPUT IF NO USER IF FOUND IN USER'S TABLE
function handleResultResponseUserName(ResponseObject) {
if (ResponseObject == "no user with this number") {
$('#frmGetRoles').find('input[name="UserName"]').val(null);
}
else {
//DO NOTHING
}
}
Here is my JsonResult in my RolesController:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult isUserValid(string username)
{
var name = string.Empty;
var CheckUserExists = (from c in _db.AspNetUsers
where (c.UserName.Equals(username))
select c);
var results = new JsonResult();
if (CheckUserExists.Any())
{
name = CheckUserExists.First().UserName;
}
else
{
name = "no user with this name in database";
}
return Json(name, JsonRequestBehavior.DenyGet);
}
I've got almost exact code working in a different application and I cut and pasted into a new one where I am trying to use it for Roles management.
The json reference is there, and in web.config. But when I put a breakpoint inside the JsonResult, it never stops there and an error is returned from the client javascript (404 resource not found). There is no other json stuff being used in this new app . . .yet.
I can hit f5 and it returns:
http://localhost/StoreMasterSecure/Roles/ManageUserRoles
which is the view that has the button that runs the ajax. It all gets to the ajax call and then nothing happens and Chrome Developer Tools console shows 404 error.
Even if I type in the URL the path, I get the resource not found 404 page:
http://localhost/StoreMaster/Roles/isValidUser/xxxx#xxx.com
(isValidUser is the JsonResult in the controller, in same controller that ManageUserRoles ActionResult exists and works)
To ensure you url's are correctly generated, use the Url.Action() method and pass the data using the ajax data option. Change your ajax to
$.ajax({
url: '#Url.Action("isUserValid", "Roles")', // change this
data: { username: thisUser }, // add this
type: 'POST',
success: handleResultResponseUserName,
error: function (xhr) { alert("Error..."); }
});
You also need to remove the [ValidateAntiForgeryToken] attibute from your controller method since you not passing the token.
Side note: MVC comes with a RemoteAttribute to handle this scenario. Refer How to: Implement Remote Validation in ASP.NET MVC which means you do not need your script.

IBM Worklight JSONStore - Add and get data

I am using worlight JSONstore. I am new to it. I tried searching that read all docs but didn't get much idea.
I have one login page from that I get some json data I want to store that data using jsonstore. and get that afterwards.
I made jsonstore adapter.
Json-Store-Impl.js
function getJsonStores(custData) {
var data = custData;
return data;
//custdata is json
}
function addJsonStore(param1) {
var input = {
method : 'put',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function updateJsonStore(param1) {
var input = {
method : 'post',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function deleteJsonStore(param1) {
var input = {
method : 'delete',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
after that I Create a local JSON store.
famlCollection.js
;(function () {
WL.JSONStore.init({
faml : {
searchFields: {"response.mci.txnid":"string","response.mci.scrnseqnbr":"string","response.loginUser":"string","request.fldWebServerId":"string","response.fldRsaImageHeight":"string","request.fldRequestId":"string","request.fldTxnId":"string","response.fldDeviceTokenFSO":"string","response.fldRsaCollectionRequired":"string","response.datlastsuccesslogin":"string","response.fldRsaUserPhrase":"string","response.fldRsaAuthTxnId":"string","response.rc.returncode":"string","response.datcurrentlogin":"string","response.mci.deviceid":"string","response.customername":"string","request.fldDeviceId":"string","response.fldRsaUserStatus":"string","request.fldScrnSeqNbr":"string","response.fldRsaImageWidth":"string","request.fldLangId":"string","response.fldTptCustomer":"string","response.encflag":"string","response.rc.errorcode":"string","response.fldRsaImagePath":"string","response.mci.appid":"string","response.mci.requestid":"string","response.rc.errormessage":"string","response.mci.appserverid":"string","response.fldRsaCollectionType":"string","request.fldAppId":"string","response.fldRsaImageId":"string","request.fldLoginUserId":"string","response.mci.sessionid":"string","response.mci.langid":"string","response.mci.remoteaddress":"string","request.fldAppServerId":"string","response.mci.webserverid":"string","response.fldRsaImageText":"string","response.fldRsaEnrollRequired":"string","response.fldRsaActivityFlag":"string"},
adapter : {
name: 'JsonStore',
replace: 'updateJsonStore',
remove: 'deleteJsonStore',
add: 'addJsonStore',
load: {
procedure: 'getJsonStores',
params: [],
key: 'faml'
},
accept: function (data) {
return (data.status === 200);
}
}
}
}, {
password : 'PleaseChangeThisPassword'
})
.then(function () {
WL.Logger.debug(['Take a look at the JSONStore documentation and getting started module for more details and code samples.',
'At this point there is no data inside your collection ("faml"), but JSONStore is ready to be used.',
'You can use WL.JSONStore.get("faml").load() to load data from the adapter.',
'These are some common JSONStore methods: load, add, replace, remove, count, push, find, findById, findAll.',
'Most operations are asynchronous, wait until the last operation finished before calling the next one.',
'JSONStore is currently supported for production only in Android and iOS environments.',
'Search Fields are not dynamic, call WL.JSONStore.destroy() and then initialize the collection with the new fields.'].join('\n'));
})
.fail(function (errObj) {
WL.Logger.ctx({pretty: true}).debug(errObj);
});
}());
When I clicked on login button I call getJsonStores like this -
getJsonStores = function(){
custData = responseData();
var invocationData = {
adapter : "JsonStore",
procedure : "getJsonStores",
parameters : [custData],
compressResponse : true
};
//WL.Logger.debug('invoke msg '+invocationData, '');
WL.Client.invokeProcedure(invocationData, {
onSuccess : sucess,
onFailure : AdapterFail,
timeout: timeout
});
};
I followed these steps
Is this right way? and how can I check jsonstore working locally or not? and how can I store my jsondata in JSONStore? Where should I initialize the wlCommonInit function in project?
plz Help me out.
Open main.js and find the wlCommonInit function, add the JSONStore init code.
WL.JSONStore.init(...)
You already have an adapter that returns the data you want to add to JSONStore, call it any time after init has finished.
WL.Client.invokeProcedure(...)
Inside the onSuccess callback, a function that gets executed when you successfully get data from the adapter, start using the JSONStore API. One high level way to write the code would be, if the collection is empty (the count API returns 0), then add all documents to the collection.
WL.JSONStore.get(collectionName).count()
.then(function (countResult) {
if(countResult === 0) {
//collection is empty, add data
WL.JSONStore.get(collectionName).add([{name: 'carlos'}, {name: 'mike'}])
.then(function () {
//data stored succesfully
});
}
});
Instead of adding [{name: 'carlos'}, {name: 'mike'}] you probably want to add the data returned from the adapter.
Later in your application, you can use the find API to get data back:
WL.JSONStore.get(collectionName).findAll()
.then(function (findResults) {
//...
});
There is also a find API that takes queries (e.g. {name: 'carlos'}), look at the getting started module here and the documentation here.
It's worth mentioning that the JSONStore API is asynchronous, you must wait for the callbacks in order to perform the next operation.

DevExtreme datasource can't load Data Service data

I tried to accomplish the tutorial here, and when I used their data service, it worked just fine.
I modified the source to my data service (WCF Data Service v5.6, OData V2), and the list just shows the Loading sign and nothing happens.
The code should load any data type, it just has to be mapped accordingly. My service is availabe through the browser, I checked.
Here is the code:
DevExTestApp.home = function (params) {
var viewModel = {
dataSource: DevExpress.data.createDataSource({
load: function (loadOptions) {
if (loadOptions.refresh) {
try {
var deferred = new $.Deferred();
$.get("http://192.168.1.101/dataservice/dataservice.svc/People")
.done(function (result) {
var mapped = $.map(result, function (data) {
return {
name: data.Name
}
});
deferred.resolve(mapped);
});
}
catch (err) {
alert(err.message);
}
return deferred;
}
}
})
};
return viewModel;
}
What else should I set?
The try-catch block would not help is this case, because data loading is async. Instead, subscribe to the fail callback:
$.get(url)
.done(doneFunc)
.fail(failFunc);
Another common problem with accessing a web service from JavaScript is Same-Origin Policy. Your OData service have to support either CORS or JSONP. Refer to this discussion.

viewbag data is empty in $.ajax

Iam using asp.net mvc4 and facing some problem in accessing viewbag.price.
This is what i am doing:-
[HttpPost]
public ActionResult FillModel(int id)
{
var vehModel = db.Vehicle_Model.Where(vehMod => vehMod.MakeID == id).ToList().Select(vehMod => new SelectListItem() { Text = vehMod.Model, Value = vehMod.pkfModelID.ToString() });
ViewBag.Price = 100;
return Json(vehModel, JsonRequestBehavior.AllowGet);
}
i am calling above using below:-
$.ajax({
url: '#Url.Action("FillModel","Waranty")',
type: 'post',
data: { id: id },
dataType: 'json',
success: function (data) {
$('#ddModel').empty();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ddModel').append(optionTag);
});
var a = '#ViewBag.Price';
},
error: function () {
alert('Error');
}
});
But i am not able to access ViewBag.Price.
Anyone know the reason??
thanks
The reason you aren't able to access items from the ViewBag inside your ajax success function is because the view that contains your script has already been rendered by the Razor view engine, effectively setting the variable a to whatever the value of #ViewBag.Price was at the time the page was rendered.
Looking at the process flow might be helpful:
(1) The request comes in for the view that has your script fragment in it.
(2) The controller method that returns your view is called.
(3) The Razor view engine goes through the view and replaces any references to #ViewBag.Price in your view with the actual value of ViewBag.Price. Assuming ViewBag.Price doesn't have a value yet, the success function in your script is now
success: function (data) {
$('#ddModel').empty();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ddModel').append(optionTag);
});
var a = '';
}
(4) The rendered html gets sent to the client
(5) Your ajax request gets triggered
(6) On success, a gets set to the empty string.
As you had mentioned in the comments of your question, the solution to this problem is to include a in the Json object returned by your action method, and access it using data.a in your script. The return line would look like
return Json(new {
model = vehModel,
a = Price
});
Keep in mind that if you do this, you'll have to access model data in your ajax success function with data.model.Field. Also, you shouldn't need to specify the JsonRequestBehavior.AllowGet option, since your method only responds to posts and your ajax request is a post.