James123
James123

Reputation: 11652

how to return exception to AJAX call from webmethod?

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
    }
}

Upvotes: 0

Views: 5550

Answers (3)

Dylan Corriveau
Dylan Corriveau

Reputation: 2557

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);
   }); 
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

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.

Upvotes: 2

cplc
cplc

Reputation: 33

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.

Upvotes: 0

Related Questions