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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

1 Comment

But How can I catch in error: function () in AJAX?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.