Get xhr object in vb.net when ajax call fails

I have a big problem in calling jQuery.ajax. I access the web service every time I click the refresh button. I have a separate web services class that has several methods. When I call the web service method, I processed the error and logged the error information in db after that, I have to override "ex" which means the error object XMLHttpRequest. Is it possible to assign an SqlExceptionajax object ( xhr) to VB.NET? Please help me it is much more useful to me.

+1
source share
1 answer

Yes it is possible! I am trying to describe it in VB.NET (I mainly use C #, but I hope I will not make syntax errors). We have a web service.

<WebMethod()> _
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function GetData(ByVal Age As Integer) As String
If Age <= 0 Then
    Throw(New ArgumentException("The parameter age must be positive."))
End If
'... some code
End Function

The same code in C # looks like

[WebMethod]
[ScriptMethod (UseHttpGet=true)]
public string GetData(int age)
{
    if (age <= 0)
        throw new ArgumentException("The parameter age must be positive.");
    // some code
}

In the case of a negative input value, an exception raises ArgumentException(everything I explain remains unchanged for another exception, such as SqlException).

You now have JavaScript code that you use jQuery.ajaxto call the service. You can then deploy the code to support exception handling as follows:

$.ajax({
    type: "GET",
    url: "MyWebService.asmx/GetData",
    data: {age: -5},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data, textStatus, xhr) {
        // use the data
    },
    error: function(xhr, textStatus, ex) {
        var response = xhr.responseText;
        if (response.length > 11 && response.substr(0, 11) === '{"Message":' &&
            response.charAt(response.length-1) === '}') {

            var exInfo = JSON.parse(response);
            var text = "Message=" + exInfo.Message + "\r\n" +
                       "Exception: " + exInfo.ExceptionType;
                      // + exInfo.StackTrace;
            alert(text);
        } else {
            alert("error");
        }
    }
});

In case of an exception, we receive information about the error in the JSON format. We deserialize it for an object that has properties Message, ExceptionTypeand StackTracethen display an error message, for example, the following

Message: The parameter age must be positive.
Exception: System.ArgumentException

, , StackTrace. Message: ExceptionType: (, System.ArgumentException System.Data.SqlClient.SqlException).

0

Source: https://habr.com/ru/post/1763424/


All Articles