Reputation: 1790
I want to return a specific message on error of an ajax request.
[WebMethod]
public static AjaxReturnObject SubmitWager(string token, string track, string race, string amount, string pool, string runners)
{
try
{
var serviceReturn = Services.Account.SubmitWager("", track, race, pool, amount, runners);
return new AjaxReturnObject(serviceReturn.AccountToken, serviceReturn.Payload);
}
catch (CustomServiceException<string> e)
{
throw new Exception(e.Message);
}
}
Debugging says that it hits my catch when I need it to, but when I look at the xhr within my jquery ajax call it ALWAYS says "There was an error processing the request."
error: function (xhr, textStatus, errorThrown) {
log(xhr, textStatus, errorThrown);
}
How can I get my desired message to comeback to the ajax call under xhr.responseText?
Upvotes: 1
Views: 10242
Reputation: 605
Try just Throw
instead of Throw new
in the catch block. and once u parse the XHR.responseText, the exception message will be contained in "Message"
For ex:
$.ajax({
type: "POST",
//... other parameters
error: function(XHR, errStatus, errorThrown) {
var err = JSON.parse(XHR.responseText);
errorMessage = err.Message;
}
});
Upvotes: 4
Reputation: 125
Perhaps the better route would be is to define the success callback of the AJAX request with code that checks a success flag:
c#
[WebMethod]
public static AjaxReturnObject SubmitWager(string token, string track, string race, string amount, string pool, string runners)
{
try
{
var serviceReturn = Services.Account.SubmitWager("", track, race, pool, amount, runners);
return new AjaxReturnObject(serviceReturn.AccountToken, serviceReturn.Payload);
}
catch (CustomServiceException<string> e)
{
return new AjaxReturnObject(0, e.Message();
}
}
Javascript
$.ajax({
...
success: function (data) {
if (data.AccountToken == 0) {
// There was an error
log(data.Payload);
}
else {
// your code
}
}
});
I offer this alternative because I'm not sure that if you throw an error in the server side code, that the function returns anything back. That error you're receiving, is client side, the error
callback really refers to whether or not the request could be made.
Upvotes: 1