jQuery Ajax error handling, show custom exception messages

前端 未结 21 2720
滥情空心
滥情空心 2020-11-22 01:50

Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?

For example, if I want to throw an exception on the server side v

相关标签:
21条回答
  • 2020-11-22 02:41

    This is what I did and it works so far in a MVC 5 application.

    Controller's return type is ContentResult.

    public ContentResult DoSomething()
    {
        if(somethingIsTrue)
        {
            Response.StatusCode = 500 //Anything other than 2XX HTTP status codes should work
            Response.Write("My Message");
            return new ContentResult();
        }
    
        //Do something in here//
        string json = "whatever json goes here";
    
        return new ContentResult{Content = json, ContentType = "application/json"};
    }
    

    And on client side this is what ajax function looks like

    $.ajax({
        type: "POST",
        url: URL,
        data: DATA,
        dataType: "json",
        success: function (json) {
            //Do something with the returned json object.
        },
        error: function (xhr, status, errorThrown) {
            //Here the status code can be retrieved like;
            xhr.status;
    
            //The message added to Response object in Controller can be retrieved as following.
            xhr.responseText;
        }
    });
    
    0 讨论(0)
  • 2020-11-22 02:43

    Make sure you're setting Response.StatusCode to something other than 200. Write your exception's message using Response.Write, then use...

    xhr.responseText
    

    ..in your javascript.

    0 讨论(0)
  • 2020-11-22 02:44

    You need to convert the responseText to JSON. Using JQuery:

    jsonValue = jQuery.parseJSON( jqXHR.responseText );
    console.log(jsonValue.Message);
    
    0 讨论(0)
提交回复
热议问题