簡體   English   中英

jQuery Ajax 錯誤處理,顯示自定義異常消息

[英]jQuery Ajax error handling, show custom exception messages

有什么方法可以在我的 jQuery AJAX 錯誤消息中將自定義異常消息顯示為警報?

例如,如果我想通過Struts在服務器端通過throw new ApplicationException("User name already exists");拋出異常throw new ApplicationException("User name already exists"); ,我想在 jQuery AJAX 錯誤消息中捕獲此消息(“用戶名已存在”)。

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);
      }
    });
  }
});

在我警告拋出的錯誤的第二個警報中,我變得undefined並且狀態代碼為 500。

我不確定我哪里出錯了。 我能做些什么來解決這個問題?

確保將Response.StatusCode設置為 200 以外的值。使用Response.Write編寫異常消息,然后使用...

xhr.responseText

..在你的javascript中。

控制器:

public class ClientErrorHandler : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        var response = filterContext.RequestContext.HttpContext.Response;
        response.Write(filterContext.Exception.Message);
        response.ContentType = MediaTypeNames.Text.Plain;
        filterContext.ExceptionHandled = true;
    }
}

[ClientErrorHandler]
public class SomeController : Controller
{
    [HttpPost]
    public ActionResult SomeAction()
    {
        throw new Exception("Error message");
    }
}

查看腳本:

$.ajax({
    type: "post", url: "/SomeController/SomeAction",
    success: function (data, text) {
        //...
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

服務器端:

     doPost(HttpServletRequest request, HttpServletResponse response){ 
            try{ //logic
            }catch(ApplicationException exception){ 
               response.setStatus(400);
               response.getWriter().write(exception.getMessage());
               //just added semicolon to end of line

           }
 }

客戶端:

 jQuery.ajax({// just showing error property
           error: function(jqXHR,error, errorThrown) {  
               if(jqXHR.status&&jqXHR.status==400){
                    alert(jqXHR.responseText); 
               }else{
                   alert("Something went wrong");
               }
          }
    }); 

通用 Ajax 錯誤處理

如果我需要為所有 ajax 請求做一些通用的錯誤處理。 我將設置 ajaxError 處理程序並在 html 內容頂部名為 errorcontainer 的 div 上顯示錯誤。

$("div#errorcontainer")
    .ajaxError(
        function(e, x, settings, exception) {
            var message;
            var statusErrorMap = {
                '400' : "Server understood the request, but request content was invalid.",
                '401' : "Unauthorized access.",
                '403' : "Forbidden resource can't be accessed.",
                '500' : "Internal server error.",
                '503' : "Service unavailable."
            };
            if (x.status) {
                message =statusErrorMap[x.status];
                                if(!message){
                                      message="Unknown Error \n.";
                                  }
            }else if(exception=='parsererror'){
                message="Error.\nParsing JSON Request failed.";
            }else if(exception=='timeout'){
                message="Request Time out.";
            }else if(exception=='abort'){
                message="Request was aborted by the server";
            }else {
                message="Unknown Error \n.";
            }
            $(this).css("display","inline");
            $(this).html(message);
                 });

您需要將responseText轉換為 JSON。 使用 JQuery:

jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);

如果調用 asp.net,這將返回錯誤消息標題:

我沒有自己寫所有的 formatErrorMessage 但我發現它非常有用。

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) ); 
})

這就是我所做的,到目前為止它在 MVC 5 應用程序中有效。

控制器的返回類型是 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"};
}

在客戶端,這就是 ajax 函數的樣子

$.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;
    }
});

如果有人像 2016 年一樣在這里尋找答案,請使用.fail()進行錯誤處理,因為.error()從 jQuery 3.0 開始已棄用

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

我希望它有幫助

通用/可重用的解決方案

提供此答案以供將來所有遇到此問題的人參考。 解決方案包括兩件事:

  1. 在服務器上驗證失敗時拋出的自定義異常ModelStateException (當我們使用數據注釋和使用強類型控制器操作參數時,模型狀態報告驗證錯誤)
  2. 自定義控制器操作錯誤過濾器HandleModelStateExceptionAttribute捕獲自定義異常並返回 HTTP 錯誤狀態,主體中包含模型狀態錯誤

這為 jQuery Ajax 調用提供了最佳基礎設施,以充分利用successerror處理程序的潛力。

客戶端代碼

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

服務端代碼

[HandleModelStateException]
public ActionResult Create(User user)
{
    if (!this.ModelState.IsValid)
    {
        throw new ModelStateException(this.ModelState);
    }

    // create new user because validation was successful
}

這篇博文詳細介紹了整個問題,您可以在其中找到在您的應用程序中運行它的所有代碼。

 error:function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
在代碼錯誤 ajax 請求中,如果您想在成功范圍內顯示您的應用程序發送的錯誤消息,則在客戶端到服務器之間連接捕獲錯誤的請求

比如

 success: function(data){ // data is object send form server // property of data // status type boolean // msg type string // result type string if(data.status){ // true not error $('#api_text').val(data.result); } else { $('#error_text').val(data.msg); } }

我發現這很好,因為我可以解析我從服務器發送的消息,並在沒有堆棧跟蹤的情況下向用戶顯示一條友好的消息......

error: function (response) {
      var r = jQuery.parseJSON(response.responseText);
      alert("Message: " + r.Message);
      alert("StackTrace: " + r.StackTrace);
      alert("ExceptionType: " + r.ExceptionType);
}

這可能是由於 JSON 字段名稱沒有引號引起的。

將 JSON 結構從:

{welcome:"Welcome"}

到:

{"welcome":"Welcome"}

此函數基本上生成唯一的隨機 API 密鑰,如果沒有,則會出現帶有錯誤消息的彈出對話框

在查看頁面中:

<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>

來自控制器:

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));
}

可選的回調參數指定在 load() 方法完成時要運行的回調函數。 回調函數可以有不同的參數:

類型:函數( jqXHR jqXHR, String textStatus, String errorThrown )

請求失敗時調用的函數。 該函數接收三個參數:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)對象、描述發生的錯誤類型的字符串和可選的異常對象(如果發生)。 第二個參數(除了 null)的可能值是“超時”、“錯誤”、“中止”和“解析器錯誤”。 當發生 HTTP 錯誤時,errorThrown 會接收 HTTP 狀態的文本部分,例如“未找到”或“內部服務器錯誤”。 從 jQuery 1.5 開始,錯誤設置可以接受函數數組。 每個函數都會被依次調用。 注意:對於跨域腳本和跨域 JSONP 請求,不會調用此處理程序。

您在 xhr 對象中有一個拋出異常的 JSON 對象。 只需使用

alert(xhr.responseJSON.Message);

JSON 對象公開了另外兩個屬性:“ExceptionType”和“StackTrace”

我相信 Ajax 響應處理程序使用 HTTP 狀態代碼來檢查是否有錯誤。

因此,如果您只是在服務器端代碼上拋出 Java 異常,但 HTTP 響應沒有 500 狀態代碼 jQuery(或者在這種情況下可能是XMLHttpRequest對象)將假設一切正常。

我這么說是因為我在 ASP.NET 中遇到了類似的問題,我拋出了類似 ArgumentException("Don't know what to do...") 但錯誤處理程序沒有觸發的問題。

然后,無論是否有錯誤,我都將Response.StatusCode設置為 500 或 200。

jQuery.parseJSON 對於成功和錯誤都很有用。

$.ajax({
    url: "controller/action",
    type: 'POST',
    success: function (data, textStatus, jqXHR) {
        var obj = jQuery.parseJSON(jqXHR.responseText);
        notify(data.toString());
        notify(textStatus.toString());
    },
    error: function (data, textStatus, jqXHR) { notify(textStatus); }
});
$("#save").click(function(){
    $("#save").ajaxError(function(event,xhr,settings,error){
        $(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url);
    });
});

使用以下命令在服務器上拋出一個新異常:

Response.StatusCode = 500

Response.StatusDescription = ex.Message()

我相信 StatusDescription 返回給 Ajax 調用......

示例:

        Try

            Dim file As String = Request.QueryString("file")

            If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")

            Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString()

            sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)

            file = IO.Path.Combine(sTmpFolder, file)

            If IO.File.Exists(file) Then

                IO.File.Delete(file)

            End If

        Catch ex As Exception

            Response.StatusCode = 500

            Response.StatusDescription = ex.Message()

        End Try

盡管問這個問題已經很多年了,但我仍然沒有找到xhr.responseText作為我正在尋找的答案。 它以以下格式返回我的字符串:

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

我絕對不想向用戶展示。 我正在尋找的是如下所示的內容:

alert(xhr.responseJSON.message);

xhr.responseJSON.message為我提供了來自 Json 對象的確切消息,可以向用戶顯示。

$("#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
    });
});

如果有任何表單提交驗證

只需使用其余的代碼

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

... ... });

首先我們需要在 web.config 中設置 <serviceDebug includeExceptionDetailInFaults="True" /> :

<serviceBehaviors> 
 <behavior name=""> 
  <serviceMetadata httpGetEnabled="true" /> 
    **<serviceDebug includeExceptionDetailInFaults="true" />** 
 </behavior> 
</serviceBehaviors>

除了在錯誤部分的 jquery 級別之外,您還需要解析包含以下異常的錯誤響應:

.error(function (response, q, t) { 
  var r = jQuery.parseJSON(response.responseText); 
}); 

然后使用 r.Message 您可以實際顯示異常文本。

檢查完整代碼: http : //www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html

就我而言,我剛剛從控制器中刪除了 HTTP VERB。

    **//[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));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM