jQuery Ajax error handling, show custom exception messages

前端 未结 21 2790
滥情空心
滥情空心 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;
        }
    });
    

提交回复
热议问题