How to handle error object from parse.com cloud callback? - javascript

I have a cloud function
Parse.Cloud.define("register", function (request, response) {
var params = request.params;
var pass1 = params.pass1;
var pass2 = params.pass2;
if (pass1.length < 8 || pass2.length < 8) {
response.error("Your password is too short!");
return;
}
});
and calling this cloud function with javascript:
function register(){
Parse.Cloud.run("register", { pass1 : "abc", pass2 : "abc", {
error: function(error){
alert("Error! --> error msg: " + error.message);
},
success: function(){
alert("Success !");
}
});
}
The problem is I cannot read the error message! I'm getting undefined object.
Error! --> error msg: undefined

When you use 'response.error("")' to return an error value, it will return the following response:
{"code":141,"error":"Your password is too short!"}
So you should get error.error instead of error.message.
function register(){
Parse.Cloud.run("register", { pass1 : "abc", pass2 : "abc", {
error: function(error){
alert("Error! --> error msg: " + error.error);
},
success: function(){
alert("Success !");
}
});
}

error.message didn't work for me one time, but it was just a bug in my code. Later error.message worked as expected.
https://www.parse.com/questions/parsepromiseerror-not-printing-the-error-message-or-code
If you use: response.error("Your password is too short!");
Then you should expect: alert("Error! --> error msg: " + error.message);
Note: For your particular issue, your cloud code might not be reaching the if statement.

I found when calling response.error() from a beforeSave Cloud Code function, the returned error was actually an array. So to access the error message, use
error[0].message

Related

Ajax result always returns error even if function is successful

I have an Ajax function that looks like this
$.ajax({
type: "POST",
url: "#IGT.baseUrl/SODetailsAjax/AddUnits",
traditional: true,
data: {
__RequestVerificationToken: token,
so_id: #Int32.Parse(Request["orderId"]),
site_id: site,
addItem_id: items,
addItem_qty: itemsqty,
addItem_disc: itemsdisc,
addComp_id: comps,
addComp_qty: compsqty,
addComp_disc: compsdisc,
addPart_id: parts,
addPart_qty: partsqty,
addPart_disc: partsdisc
},
success: function (data) {
if(data.success === "False"){
var errorMessage = data.Message;
alert("Error:" + errorMessage);
return;
}
if(data.success === "True"){
location.href = "../SalesOrders/Details?id=#so.ID";
}
},
error: function (jqXHR, status, error) {
alert("Error:" + error);
}
});
And I have a JSON ActionResult method that does this in it.
if (!canCreate)
{
var errorMessage = string.Join(",", errors);
var stock = new { success = "False", Message = errorMessage };
return Json(stock, JsonRequestBehavior.AllowGet);
}
else
{
var result = new { success = "True" };
return Json(result, JsonRequestBehavior.AllowGet);
}
But everytime Success is true it returns an error message saying "Error:Not defined" when I click "OK" it proceeds. But how can I make it so it just proceeds instead of sending an error message?
You have a couple of errors. In your if (data.Success = "false") statement, this is not a condition. This is an assignment. You should do if (data.success === "false") this would check for the condition. Also note that "success" is all lower case because it's converted to Json. You also need to note that "False" does not equal "false" so you must pick a casing. Either do "False"/"True" in both c# and JavaScript or "false"/"true".

Parse Cloud result object is empty

I got this problem yesterday, couldn't resolved it myself.
Here is my parse.com cloud code :
Parse.Cloud.define("getWorkerInfo", function(request, response) {
Parse.Cloud.useMasterKey();
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo(request.params.userObjectId);
userQuery.select("firstName", "lastName", "username");
userQuery.first({
success : function(result){
var currentUser = {
"firstName" : result.firstName,
"lastName" : result.lastName,
"username" : result.username
};
response.success(currentUser);
},
error : function(error){
response.error(error);
}
});
});
and result to chrome dev tools command :
result : {}
this code for using result from first code wrote this question :
function get(userObjectId) {
Parse.Cloud.run("getWorkerInfo", { "userObjectId" : userObjectId }, {
success: function(result){
return result;
}
,
error : function(err){
console.log(err);
}
});
}
I also changed to response data - user query directly.
Response action is okay.
But Couldn't retrieved that itself :
result = ParseUser {_objCount: 2, className: "_User", id: "iNneJil9XW"}
What I missing, and can I find answer this problem?
Thanks Clark, there's a lot going on in this question. Try hard coding the result just to make sure the execution flow/path is correct and the environment is set up correctly. For example,
Parse.Cloud.define("getWorkerInfo", function(request, response) {
Parse.Cloud.useMasterKey();
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo(request.params.userObjectId);
userQuery.select("firstName", "lastName", "username");
userQuery.first({
success : function(result){
response.success("1234");
},
error : function(error){
response.error(error);
}
});
});

Parse Cloud Code Mandrill Promise

So I am having an issue migrating away from Mailgun and start using Mandrill. I followed the Parse Purchase application tutorial and have a very similar code base. Here is what it currently is and successfully runs.
return Mailgun.sendEmail({
to: currentUser.get('email'),
from: hostEmail,
subject: 'Your ticket(s) purchase for ' + eventObject.get('title') + ' was successful!',
text: body
}).then(null, function(error) {
return Parse.Promise.error('Your purchase was successful, but we were not able to send you an email.');
});
So this runs successfully, no errors are thrown.
So heres the Mandrill equivalent,
return Mandrill.sendEmail({
message: {
text: body,
subject: 'Your ticket(s) purchase for ' + eventObject.get('title') + ' was successful!',
from_email: hostEmail,
from_name: appname,
to: [{
email: currentUser.get('email'),
name: currentUser.get('displayName')
}]
},
async: true
}).then(null, function(error) {
console.log('Sending email failed. Error: ' + error);
return Parse.Promise.error('Your purchase was successful, but we were not able to send you an email.');
});
Apparently, this is not working.
The error log shows:
Error: TypeError: Cannot read property 'success' of undefined
at Object.exports.sendEmail (mandrill.js:55:21)
at main.js:115:25
at e (Parse.js:2:6670)
at Parse.js:2:6119
at Array.forEach (native)
at Object.x.each.x.forEach [as _arrayEach] (Parse.js:1:661)
at c.extend.resolve (Parse.js:2:6070)
at Parse.js:2:6749
at e (Parse.js:2:6670)
at Parse.js:2:6119 (Code: 141, Version: 1.6.0)
So I think Mandrill successfully sends the email because its searching for the 'success' property, but the Promise is always failing and returns an error response back to the iOS app.
Any help will be appreciated!
Thanks again
Found the problem. Apparently you have to actually declare a promise variable and send it the success/failure callbacks.
The gist link I posted in the comments is what helped megist Link
Heres what I do now,
Parse.Cloud.define('purchase', function(request, response) {
...
...
...
var message = {
text: body,
subject: 'Your ticket(s) purchase for ' + eventObject.get('title') + ' was successful!',
from_email: hostEmail,
from_name: appname,
to: [{
email: currentUser.get('email'),
name: currentUser.get('displayName'),
}]
};
return sendMandrillEmailPromise(message).then(null, function(error) {
console.log('Sending email failed. Error: ' + error);
return Parse.Promise.error('Your purchase was successful, but we not able to send you an email');
...
...
...
});
var sendMandrillEmailPromise = function(message){
var promise = new Parse.Promise();
Mandrill.sendEmail({
message: message,
async: true,
},{
success: function(httpResponse) {
promise.resolve(httpResponse);
},
error: function(error) {
promise.error(error);
}
});
return promise;
}
Works as expected and I got an AWESOME email! Thanks guys for your input!

Can't send an email with Parse Cloud Code and Mandrill

New to coding and never used Cloud Code before.
I need to send a confirmation email when someone submits their email in a form on my webpage with Parse Cloud Code but I can't get it to work. I'm using the Mandrill Cloud Module to send the emails.
My questions are -
a) Am I calling the Cloud Function correctly?
b) The only variable that changes is the persons email address. Am I passing that variable correctly?
Example code would really help.
Thanks
Here's my Cloud Code:
Parse.Cloud.define("introEmail", function(request, response) {
var Mandrill = require('mandrill');
Mandrill.initialize('*************');
mandrill.sendEmail({
message: {
text: "Hello!",
subject: "Thanks for Signing Up!",
from_email: "Test#Test.com",
from_name: "Chad",
to: [
{
email: request.params.Address,
name: ""
}
]
},
async: true
}, {
success: function(httpResponse) { response.success("Email sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
Here's my JS code:
$(".input-group-btn").click(function() {
console.log("Notify Me");
var Address = $(".form-control").val();
var Email = Parse.Object.extend("Email");
var email = new Email();
email.set("Address", Address);
console.log(Address);
email.save(null, {
success: function(email) {
console.log('New object created with objectId: ' + email.id);
Parse.Cloud.run(introEmail,Address)
},
error: function(email, error) {
alert('Could not accept email address: ' + error.message);
}
});
});
a) Call the Cloud function with Parse.Cloud.run(), however, you must pass name, data, options. These are 'introEmail' (the name of the cloud function), the variable which is {Address: $(".form-control").val()} and the success/error handlers.
b)See a
Parse.Cloud.define("introEmail", function(request, response) {
var mandrill = require("mandrill");
mandrill.initialize('*************');
mandrill.sendEmail({
message: {
text: "Hello!",
subject: "Thanks for Signing Up!",
from_email: "Test#Test.com",
from_name: "Test",
to: [
{
email: request.params.Address,
name: ""
}
]
},
async: true
}, {
success: function(httpResponse) { response.success("Email sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
Here's the JS for the client-side:
$(".input-group-btn").click(function() {
console.log("Notify Me");
var Address = $(".form-control").val();
var Email = Parse.Object.extend("Email");
var email = new Email();
email.set("Address", Address);
console.log(Address);
email.save(null, {
success: function(email) {
// Execute any logic that should take place after the object is saved.
console.log('New object created with objectId: ' + email.id);
// Invoke our cloud function, using the phone number in the text field
Parse.Cloud.run('introEmail', {
Address: $(".form-control").val()
}, {
// Success handler
success: function(message) {
alert('Success: ' + message);
},
// Error handler
error: function(message) {
alert('Error: ' + message);
}
});
}
});
});

Ajax function give error "Hit error fn! [object Object]" from the following function when calling a webservice

i am new to the webservice and try to call a webservice from html page which give me following error "Hit error fn![object Object]" and cannot sending mail to the desired email address. kindly tell me that whats the error?
function test() {
var firstname=$('#txtName').val();
var lastname =$('#txtMessage').val();
var Email=$('#txtEmail').val();
$.ajax({ url: "http://localhost/ZeroDebt/WsZeroDebtApp.asmx/SendEmailToClient",
data: { _fromAddress: JSON.stringify(Email),_Subject:JSON.stringify("Zero Debt App Invitation Request"),_body:JSON.stringify(firstname +' '+lastname), clientName: JSON.stringify('Dr. Hanoi'), clientEmail: JSON.stringify('abc#xyz.net') },
dataType: "jsonp",
success: function(data) {
alert(data);
},
error: function(error) {
alert("Hit error fn!" + error);
}
});
}
May I suggest to rewrite as such? (Please test yourself)
var SENDMAIL_URL = "http://localhost/ZeroDebt/WsZeroDebtApp.asmx/SendEmailToClient"
function test() {
var firstname = $('#txtName').val(),
lastname = $('#txtMessage').val(),
email = $('#txtEmail').val();
var data = JSON.stringify({
_fromAddress: email,
_Subject: "Zero Debt App Invitation Request",
_body: firstname + ' ' + lastname,
_clientName: 'Dr. Hanoi',
clientEmail: 'abc#xyz.net'
});
function notify( args ) {
console.log( args );
}
function onSuccess( data ) {
notify( data );
}
function onError( error ) {
notify( "Hit error fn!" ); // Important to seperate string from Object
notify( error );
}
$.ajax({
url: SENDMAIL_URL,
data: data,
dataType: "jsonp",
success: onSuccess,
error: onError
});
}
Furthermore it would be maintainable to make your URL a constant string and keep urls together (easier configurable than scrolling through code).
At last, i found a solution. the only thing i need to do is to give email at client email parameter that would not be in string format. write abc#xyz.com instead of "abc#xyz.com".
the correct scenario is:
data: { _fromAddress: JSON.stringify(Email),_Subject:JSON.stringify("Zero Debt App Invitation Request"),_body:JSON.stringify(firstname +' '+lastname), clientName: JSON.stringify('Dr. Hanoi'), clientEmail: abc#xyz.net }

Categories

Resources