I start deploying an offline application on iPhones, but it's still under heavy developpment.
I have a simple error handler for my query :
db.transaction(tx) {
tx.executeSql("SELECT * FROM TABLE",[], successHandler, errorHandler);
});
function errorHandler(transaction, error) {
alert("Error : " + error.message);
}
When I test myself the application, and get an error, I manage to find what was the query generating the error. But when it's my users (distant users, of course), it's very difficult, as the error messages are not specific.
Is there a way to add context info to my error messages, for example the sql query, or a comment parameter ?
You could use a pattern like this:
db.transaction(tx) {
doQuery(tx, "SELECT * FROM TABLE",[],theSuccessHandler)
});
function doQuery(tx, query, values, successHandler) {
tx.executeSql(query, values, successHandler, errorHandler);
function errorHandler(transaction, error) {
alert("Error : " + error.message + " in " + query);
}
}
I ehanced Myrne answer to add query parameters and a free context string :
function doQuery(tx, query, values, successHandler, context)
{
tx.executeSql(query, values, successHandler, errorHandler);
function errorHandler(transaction, error)
{
var text_context = context != undefined && context != "" ? "(" + context + ") " : "";
alert("Error "+text_context+": " + error.message + " in " + query + " (params : "+values.join(", ")+")");
}
}
This will return this kind of error :
Error (function update_commande) : could not prepare statement (1 no such column: field3) in UPDATE table SET field2 = ?, field3 = ? WHERE field1 = ? (params : 1.63, 1449, 606)
Related
I am getting Reference Error: variable is not defined error when I am trying to pass variable from one function to another in JavaScript ( postman)
Error : ReferenceError: isinDB is not defined
//Verify ISIN with DB API
pm.test("Row : " + i + "-"+dataArr[1] + ":Verify symbol isin with DB API", function () {
console.log("isin " + dataArr[6]);
//Getting isin from DB API
pm.sendRequest("http://192.168.xx.xxx:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response ) {
var resBoday = response.json()
var isinDB = resBoday.items[0].isin_code;
console.log("isinDB "+isinDB);
});
pm.expect(dataArr[6]).is.to.equals(isinDB);
});
isinDB is declared in the function callback, so it is not defined in the outer scope. Even if you declare it in the outer scope, it will not be available till the callback with response is called. Maybe you can test in callback, this way?
//Verify ISIN with DB API
pm.test("Row : " + i + "-"+dataArr[1] + ":Verify symbol isin with DB API", function () {
console.log("isin " + dataArr[6]);
//Getting isin from DB API
pm.sendRequest("http://192.168.xx.xxx:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response ) {
var resBoday = response.json()
var isinDB = resBoday.items[0].isin_code;
console.log("isinDB "+isinDB);
pm.expect(dataArr[6]).is.to.equals(isinDB);
});
});
issue fixed from below code .. thanks for the support
//Verify ISIN with DB API
pm.test("Row : " + i + " - " + dataArr[1] + " : Verify symbol isin with DB API", function () {
var isinC = dataArr[6];
console.log("isin " + dataArr[6]);
//Getting isin from DB API
pm.sendRequest("http://192.168.xx.xxx:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response) {
var resBoday = response.json()
var isinDB = resBoday.items[0].isin_code;
console.log("isinDB " + isinDB);
//pm.expect(dataArr[6]).is.to.equals(isinDB);
console.log("test" + isinC);
pm.expect(isinC).is.to.equals(isinDB);
});
});
I'm playing around with the Parse backend and NodeJS but I have a problem right now and I am not able to figure it out. I have a get request like this.
app.get("/movie", function (req, res) {
var Review = Parse.Object.extend("Review");
var query = new Parse.Query(Review);
var movie = req.query.movie;
query.equalTo("movie", movie);
query.first({
success: function (movie) {
console.log("Success");
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});});
This works fine but the error handling kinda doesn't. If, for example, I change
query.equalTo("movie", movie);
to query.equalTo("movie", "xyz");
or query.equalTo("abc", "xyz");
which does not exist in my table, I'm still getting the success statement. And yes, I have restarted the server every time.
Update
I tried the same query using the iOS SDK(Swift) and here I get into the error case. I always get the same error though, which shouldn't be, but at least I get an error while in the JS sample I always get into the success case.
I believe query.first() will not error if it does not find a "first" object. You can check for (movie == null) on the success return.
Update:
Try writing it this way:
app.get("/movie", function (req, res) {
var movie = req.query.movie;
var query = new Parse.Query("Review");
query.equalTo("movie", movie);
query.first().then(function (movie) {
// Success
console.log("Success");
}, function (error) {
// Error
console.log("Error: " + error.code + " " + error.message);
});
});
query.find() always success even if there is no match data in your table/collections
Let's try it
query.find().then(function (movies) {
if(movies.length > 0){
console.log("success");
}else{
console.log("query success but no data found");
}
}, function (error) {
// Error
console.log("Error: " + error.code + " " + error.message);
});
I couldn't able to remove the double quotes from json string. Following is my code.
var values = {};
$.each($('#regForm :input'), function(i, field) {
if (field.name == "submit") {
delete field.name;
} else {
values[field.name] = field.value;
}
});
var json_text = JSON.stringify(values);
var global = JSON.parse(json_text);
console.log(global);
$.ajax({
type : "POST",
dataType : "JSON",
data : global,
url : "http://localhost:8080/SpringRestServices/register",
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Accept-Encoding", "utf-8");
xhr.setRequestHeader("Content-type", "application/json");
},
success : function(data) {
alert("success"+data);
console.log("Success:", data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("HI");
alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown + xhr.responseText*/);
alert("readyState: " + xhr.readyState);
alert("responseText: "+ xhr.responseText);
alert("status: " + xhr.status);
alert("text status: " + textStatus);
alert("error: " + errorThrown);
}
});
Here is my output when I see it in the firefox debugger:
"{"username":"hi","email":"hi#gmail.com","password":"123"}"
I need the actual result:
{"username":"hi","email":"hi#gmail.com","password":"123"}
Can anyone help me on this.
This is my server code:
#RequestMapping(value = "/register", method = RequestMethod.POST)
#ResponseBody
public RegisterResponse newAccount(#RequestBody Register registration) {
String newAccountSql = "INSERT INTO register (email,password,username) VALUES (:email,:password,:username)";
RegisterResponse regResponse = new RegisterResponse();
regResponse.setResult(-1);
// ServiceDataBean<AuthToken> retBean = new
// ServiceDataBean<AuthToken>();
try {
System.out.println("register service calling.....");
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
namedParameters.addValue("email", registration.getEmail());
messageDigest = MessageDigest.getInstance("MD5");
byte[] md5 = new byte[64];
messageDigest.update(
registration.getPassword().getBytes("iso-8859-1"), 0,
registration.getPassword().length());
md5 = messageDigest.digest();
namedParameters.addValue("password", convertedToHex(md5));
namedParameters.addValue("username", registration.getUsername());
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
// TODO what to do with the updInt also check it's not -1
int updInt = jdbcTemplate.update(newAccountSql, namedParameters,
generatedKeyHolder);
regResponse.setResult(0);
System.out.println("from register");
} catch (Throwable e) {
regResponse.setResult(001);
e.printStackTrace();
}
return regResponse;
}
Try
json_text= json_text.slice(1, json_text.length-1);
See if writing your ajax request like this helps. It removes the explicit dataType that I think could be causing you an issue and also removes the beforeSend function and replaces it with the built in contentType option (and removes the explicit return datatype).
$.ajax({
type : "POST",
data : global, //Or json_text, whichever worked.
url : "http://localhost:8080/SpringRestServices/register",
contentType : "application/json",
success : function(data) {
alert("success"+data);
console.log("Success:", data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("HI");
alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown + xhr.responseText*/);
alert("readyState: " + xhr.readyState);
alert("responseText: "+ xhr.responseText);
alert("status: " + xhr.status);
alert("text status: " + textStatus);
alert("error: " + errorThrown);
}
});
I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link
Example :
success: function (data) {
// assuming that everything is correct and there is no exception being thrown
// output string {"d":"{"username":"hi","email":"hi#gmail.com","password":"123"}"}
// now we need to remove the double quotes (as it will create problem and
// if double quotes aren't removed then this JSON string is useless)
// The output string : {"d":"{"username":"hi","email":"hi#gmail.com","password":"123"}"}
// The required string : {"d":{username:"hi",email:"hi#gmail.com",password:"123"}"}
// For security reasons the d is added (indicating the return "data")
// so actually we need to convert data.d into series of objects
// Inbuilt function "JSON.Parse" will return streams of objects
console.log(data); // output : Object {d="{"username":"hi","email":"hi#gmail.com","password":"123"}"}
console.log(data.d); // output : {"username":"hi","email":"hi#gmail.com","password":"123"} (accessing what's stored in "d")
console.log(data.d[0]); // output : { (just accessing the first element of array of "strings")
var content = JSON.parse(data.d); // output : Object {username:"hi",email:"hi#gmail.com",password:"123"}" (correct)
console.log(content.username); // output : hi
var _name = content.username;
alert(_name); // hi
}
I'm using html5sql.com for doing html5 DB stuff :o)
- Really a great module...
However, I got stuck!
At my index.html/index.js I create my database and tables in it.
try {
html5sql.openDatabase("com.dynamicvenues.fairkeyMobile.db","Questionnaire",3*1024*1024);
html5sql.process(
[
"CREATE TABLE IF NOT EXISTS Questionnaire (uid INTEGER, json TEXT, hash TEXT);",
"CREATE TABLE IF NOT EXISTS Answers (id INTEGER PRIMARY KEY, visitor_id TEXT, json TEXT);"
],
function(){
console.log("Success Creating Tables");
},
function(error, statement){
console.error("Error: " + error.message + " when processing " + statement);
}
)
} catch(error) {
alert("Database create failed: "+error.message);
}
And further in the same page I populate one table with data:
jQuery.get(serverHttp+"json.php?exhibitorID="+exhibitorID, function(data){
var html = $(data).map(function() {
return $(this).html();
});
var jsonStr = html[0];
var exhibitorID = html[1];
var hashStr = html[2];
var SQL = "INSERT INTO Questionnaire (uid, json, hash) VALUES ("+exhibitorID+",'"+jsonStr+"','"+hashStr+"')";
try {
html5sql.process(SQL,
function(){
console.log('Inserted 1 row!');
},
function(){
console.error("Error: " + error.message + " when processing " + statement);
}
)
} catch(error) {
alert("Query failed: "+error);
}
Now, in a different page called questionnaire.html/questionnaire.js I'm trying to retrieve the data I stored in the table Questionnaire.
html5sql.process(
["SELECT * FROM Questionnaire;"],
function(transaction, results, rowsArray){
for(var i = 0; i < rowsArray.length; i++){
var uid = rowsArray[i].uid;
var json = rowsArray[i].json;
var hash = rowsArray[i].hash;
console.log("Retrieved rows: "+uid+" - "+json+" "+hash);
}
console.log("Done selecting data");
},
function(error, statement){
console.error(error.message+" Occured while processing: "+statement);
}
);
What am I doing wrong???
Regards,
Daniel
Solved! Inserted: html5sql.openDatabase("com.dynamicvenues.fairkeyMobile.db","Questionnaire",3*1024*1024); Before html5sql.process() at questionnaire.js
I try to create HTML5 table in WebOS using following JavaScript, but the table is not created.
However i can't see any further detail in the log other than the first Mojo.log "Try to create database".
2011-01-25T15:48:50.251507Z [43854] qemux86 user.notice LunaSysMgr: {LunaSysMgrJS}: com.palm.phonegap: Info: Try to create database, palmInitFramework347:2527
Do you have any idea?
Thanks..
var db;
function openDb(){
var shortName = 'mcrm';
var version = '1.0';
var displayName = 'mCRM'
var maxSize = 65536;
db = openDatabase(shortName, version, displayName, maxSize);
try {
db.transaction(
function(transaction) {
Mojo.Log.info("Try to create database");
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS bookmarks'
+ ' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '
+ ' resource_id INTEGER NOT NULL '
+ ' resource_type TEXT NOT NULL '
+ ' url TEXT NOT NULL );',
function() {
Mojo.Log.info("DATABASE CREATED");
},
errorHandler
);
}
);
Mojo.Log.info("Is it no error?");
}
function errorHandler(transaction, error) {
Mojo.Log.info("ooopss. Error was ", error.message , " ;Error code:", error.code);
return true;
}
the cause of log file is not giving err message i.e. missing one argument of executeSql
the cause of the error i.e. missing comma at CREATE TABLE statement