jQuery Ajax error handling, show custom exception

2018-12-31 05:51发布

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 via Struts by throw new ApplicationException("User name already exists");, I want to catch this message ('user name already exists') in the jQuery AJAX error message.

jQuery("#save").click(function () {
  if (jQuery('#form').jVal()) {
    jQuery.ajax({
      type: "POST",
      url: "saveuser.do",
      dataType: "html",
      data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)),
      success: function (response) {
        jQuery("#usergrid").trigger("reloadGrid");
        clear();
        alert("Details saved successfully!!!");
      },
      error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
      }
    });
  }
});

On the second alert, where I alert the thrown error, I am getting undefined and the status code is 500.

I am not sure where I am going wrong. What can I do to fix this problem?

20条回答
弹指情弦暗扣
2楼-- · 2018-12-31 05:57

You have a JSON object of the exception thrown, in the xhr object. Just use

alert(xhr.responseJSON.Message);

The JSON object expose two other properties: 'ExceptionType' and 'StackTrace'

查看更多
人间绝色
3楼-- · 2018-12-31 05:58

If someone is here as in 2016 for the answer, use .fail() for error handling as .error() is deprecated as of jQuery 3.0

$.ajax( "example.php" )
  .done(function() {
    alert( "success" );
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    //handle error here
  })

I hope it helps

查看更多
泛滥B
4楼-- · 2018-12-31 05:58

Although it has been many years since this question is asked, I still don't find xhr.responseText as the answer I was looking for. It returned me string in the following format:

"{"error":true,"message":"The user name or password is incorrect"}"

which I definitely don't want to show to the users. What I was looking for is something like below:

alert(xhr.responseJSON.message);

xhr.responseJSON.message gives me the exact message from the Json Object which can be shown to the users.

查看更多
墨雨无痕
5楼-- · 2018-12-31 06:01
$("#save").click(function(){
    $("#save").ajaxError(function(event,xhr,settings,error){
        $(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url);
    });
});
查看更多
孤独寂梦人
6楼-- · 2018-12-31 06:03

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;
    }
});
查看更多
长期被迫恋爱
7楼-- · 2018-12-31 06:04

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.

查看更多
登录 后发表回答