0

I am returning List<strings> from [WebMethod]. But when exception occurs how to return failure message to AJAX caller?. Now I am getting build error.

JS:

$.ajax({
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    url: 'new.aspx/GetPrevious',
    data: "{'name':'" + username + "'}",
    async: false,
    success: function (data) {
        Previous = data.d;
        alert(salts);
    },
    error: function () {
        alert("Error");
    }
});

C#:

[WebMethod]
public static List<string> GetPreviousSaltsAndHashes(string name)
{
    try
    {
        List<string> prevSalts = new List<string>();
        if (reader.HasRows)
        {
            while (reader.Read())
            {                      
                prevSalts.Add(reader.GetString(0));
            }
        }
        conn.Close();
        return prevSalts;
    }
    catch (Exception ex)
    {
        return "failure"; //error showing here
    }
}
Dylan Corriveau
  • 2,561
  • 4
  • 29
  • 36
James123
  • 11,184
  • 66
  • 189
  • 343

3 Answers3

2

All exceptions thrown from a WebMethod get automatically serialized to the response as a JSON representation of a .NET Exception instance. You may checkout the following article for more details.

So your server side code could be a bit simplified:

[WebMethod]
public static List<string> GetPreviousSaltsAndHashes(string name)
{
    List<string> prevSalts = new List<string>();

    // Note: This totally sticks. It's unclear what this reader instance is but if it is a 
    // SqlReader, as it name suggests, it should probably be wrapped in a using statement
    if (reader.HasRows)
    {
        while (reader.Read())
        {                      
            prevSalts.Add(reader.GetString(0));
        }
    }

    // Note: This totally sticks. It's unclear what this conn instance is but if it is a 
    // SqlConnection, as it name suggests, it should probably be wrapped in a using statement
    conn.Close();

        return prevSalts;
    }
}

and on the client side:

error: function (xhr, status, error) {
    var exception = JSON.parse(xhr.responseText);
    // exception will contain all the details you might need. For example you could
    // show the exception Message property
    alert(exception.Message);
}

And at the end of the day, after saying all this stuff, you should be aware that WebMethods are a completely outdated and obsolete technology and unless you are maintaining some existing code, you have absolutely no excuse on using them in new projects.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Make sure you are returning the same type in both circumstances. Change your failure to a list:

List<string> prevSalts = new List<string>();
try
{
    ...
}
catch (Exception ex)
{
    prevSalts.Clear();
    prevSalts.Add("failure");     
}
return Json(new 
{
    salts = prevSalts
}, JsonRequestBehavior.AllowGet);

Edit: to get your strings in the front end, check it in the appropriate method

success: function (data) {
    Previous = data.salts
    alert(salts);
},
error: function (data) {
   $.each(data.salts, function(index,item) {
        alert(item);
   }); 
}
Dylan Corriveau
  • 2,561
  • 4
  • 29
  • 36
0

You could return a generic structure with a body (your actual data), a status code and an error field to describe the exception if any. Then on the JS side you just have to use either the body or the error field depending on the status code. That is what I used in my last soap webservice.

cplc
  • 33
  • 1
  • 5