jQuery Ajax error handling, show custom exception messages

前端 未结 21 2794
滥情空心
滥情空心 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:29
    $("#fmlogin").submit(function(){
       $("#fmlogin").ajaxError(function(event,xhr,settings,error){
           $("#loading").fadeOut('fast');       
           $("#showdata").fadeIn('slow');   
           $("#showdata").html('Error please, try again later or reload the Page. Reason: ' + xhr.status);
           setTimeout(function() {$("#showdata").fadeOut({"opacity":"0"})} , 5500 + 1000); // delays 1 sec after the previous one
        });
    });
    

    If there is any form is submit with validate

    simply use the rest of the code

    $("#fmlogin").validate({...
    

    ... ... });

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

    A general/reusable solution

    This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:

    1. Custom exception ModelStateException that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)
    2. Custom controller action error filter HandleModelStateExceptionAttribute that catches custom exception and returns HTTP error status with model state error in the body

    This provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success and error handlers.

    Client side code

    $.ajax({
        type: "POST",
        url: "some/url",
        success: function(data, status, xhr) {
            // handle success
        },
        error: function(xhr, status, error) {
            // handle error
        }
    });
    

    Server side code

    [HandleModelStateException]
    public ActionResult Create(User user)
    {
        if (!this.ModelState.IsValid)
        {
            throw new ModelStateException(this.ModelState);
        }
    
        // create new user because validation was successful
    }
    

    The whole problem is detailed in this blog post where you can find all the code to run this in your application.

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

    In my case, I just removed HTTP VERB from controller.

        **//[HttpPost]**   ---- just removed this verb
        public JsonResult CascadeDpGetProduct(long categoryId)
        {
           
            List<ProductModel> list = new List<ProductModel>();
            list = dp.DpProductBasedOnCategoryandQty(categoryId);
            return Json(new SelectList(list, "Value", "Text", JsonRequestBehavior.AllowGet));
        }
    
    0 讨论(0)
  • 2020-11-22 02:34

    This function basically generates unique random API key's and in case if it doesn't then pop-up dialog box with error message appears

    In View Page:

    <div class="form-group required">
        <label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
        <div class="col-sm-6">
            <input type="text" class="apivalue"  id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />                                                                    
            <button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
        </div>
    </div>
    
    <script>
    $(document).ready(function(){
        $('.changeKey1').click(function(){
              debugger;
            $.ajax({
                    url  :"index.php?route=account/apiaccess/regenerate",
                    type :'POST',
                    dataType: "json",
                    async:false,
                    contentType: "application/json; charset=utf-8",
                    success: function(data){
                      var result =  data.sync_id.toUpperCase();
                            if(result){
                              $('#api_text').val(result);
                            }
                      debugger;
                      },
                    error: function(xhr, ajaxOptions, thrownError) {
                      alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                    }
    
            });
        });
      });
    </script>
    

    From Controller:

    public function regenerate(){
        $json = array();
        $api_key = substr(md5(rand(0,100).microtime()), 0, 12);
        $json['sync_id'] = $api_key; 
        $json['message'] = 'Successfully API Generated';
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
    

    The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:

    Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

    A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

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

    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

    0 讨论(0)
  • 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) ); 
    })
    
    0 讨论(0)
提交回复
热议问题