jQuery Ajax error handling, show custom exception messages

前端 未结 21 2804
滥情空心
滥情空心 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:39

    If making a call to asp.net, this will return the error message title:

    I didn't write all of formatErrorMessage myself but i find it very useful.

    function formatErrorMessage(jqXHR, exception) {
    
        if (jqXHR.status === 0) {
            return ('Not connected.\nPlease verify your network connection.');
        } else if (jqXHR.status == 404) {
            return ('The requested page not found. [404]');
        } else if (jqXHR.status == 500) {
            return ('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
            return ('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
            return ('Time out error.');
        } else if (exception === 'abort') {
            return ('Ajax request aborted.');
        } else {
            return ('Uncaught Error.\n' + jqXHR.responseText);
        }
    }
    
    
    var jqxhr = $.post(addresshere, function() {
      alert("success");
    })
    .done(function() { alert("second success"); })
    .fail(function(xhr, err) { 
    
        var responseTitle= $(xhr.responseText).filter('title').get(0);
        alert($(responseTitle).text() + "\n" + formatErrorMessage(xhr, err) ); 
    })
    

提交回复
热议问题