782

jQuery AJAX エラー メッセージでカスタム例外メッセージをアラートとして表示する方法はありますか?

たとえば、Struts byを介してサーバー側で例外をスローしたい場合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);
      }
    });
  }
});

スローされたエラーを警告する 2 番目のアラートではundefined、ステータス コードは 500 です。

どこが間違っているのかわかりません。この問題を解決するにはどうすればよいですか?

4

21 に答える 21

378

Response.StatusCode200 以外の値に設定していることを確認してくださいResponse.Write

xhr.responseText

..あなたのJavaScriptで。

于 2009-01-16T14:25:15.607 に答える
243

コントローラ:

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);
    }
});
于 2010-05-10T07:16:07.117 に答える
102

サーバ側:

     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);
                 });
于 2012-02-25T17:09:21.253 に答える
85

responseTextを JSONに変換する必要があります。JQuery の使用:

jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);
于 2011-04-13T15:49:25.120 に答える
25

2016年のように答えのために誰かがここにいる場合は、jQuery 3.0の時点で非推奨になっている.fail()エラー処理に使用してください.error()

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

役立つことを願っています

于 2016-12-13T17:41:33.713 に答える
22

これは私が行ったことであり、これまでのところ 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-05-18T22:23:57.197 に答える
17

一般的/再利用可能なソリューション

この回答は、この問題に遭遇したすべての人への将来の参照用に提供されています。ソリューションは次の 2 つで構成されます。

  1. サーバーで検証が失敗したときにスローされるカスタム例外 ModelStateException(データ注釈を使用し、厳密な型のコントローラー アクション パラメーターを使用すると、モデル状態が検証エラーを報告します)
  2. HandleModelStateExceptionAttributeカスタム例外をキャッチし、本体にモデル状態エラーを含む HTTP エラー ステータスを返すカスタム コントローラー アクション エラー フィルター

successこれにより、jQuery Ajax 呼び出しがおよびerrorハンドラーでその可能性を最大限に活用するための最適なインフラストラクチャが提供されます。

クライアント側のコード

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

問題全体は、このブログ投稿で詳しく説明されており、アプリケーションでこれを実行するためのすべてのコードを見つけることができます。

于 2011-05-05T08:27:10.267 に答える
15

サーバーから送信していたメッセージを解析し、スタックトレースなしでユーザーにわかりやすいメッセージを表示できるため、これは素晴らしいと思いました...

error: function (response) {
      var r = jQuery.parseJSON(response.responseText);
      alert("Message: " + r.Message);
      alert("StackTrace: " + r.StackTrace);
      alert("ExceptionType: " + r.ExceptionType);
}
于 2011-12-01T21:33:03.460 に答える
9

この関数は、基本的に一意のランダムな 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));
}

オプションの callback パラメータは、load() メソッドが完了したときに実行するコールバック関数を指定します。コールバック関数には、さまざまなパラメーターを指定できます。

タイプ: 関数( jqXHR jqXHR, String textStatus, String errorThrown )

リクエストが失敗した場合に呼び出される関数。この関数は 3 つの引数を受け取ります。jqXHR (jQuery 1.4.x では XMLHttpRequest) オブジェクト、発生したエラーの種類を説明する文字列、およびオプションの例外オブジェクト (発生した場合) です。2 番目の引数 (null 以外) に指定できる値は、"timeout"、"error"、"abort"、および "parsererror" です。HTTP エラーが発生すると、errorThrown は「Not Found」や「Internal Server Error」などの HTTP ステータスのテキスト部分を受け取ります。jQuery 1.5 以降、エラー設定は関数の配列を受け入れることができます。各関数が順番に呼び出されます。注: このハンドラは、クロスドメイン スクリプトおよびクロスドメイン JSONP リクエストでは呼び出されません。

于 2018-02-21T13:04:56.280 に答える
7

これはおそらく、JSON フィールド名に引用符がないことが原因です。

JSON 構造を次のように変更します。

{welcome:"Welcome"}

に:

{"welcome":"Welcome"}
于 2010-08-14T13:01:55.247 に答える
5

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); }
});
于 2011-08-11T22:18:36.847 に答える
4
$("#save").click(function(){
    $("#save").ajaxError(function(event,xhr,settings,error){
        $(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url);
    });
});
于 2014-03-06T18:07:29.630 に答える
3

以下を使用してサーバーに新しい例外をスローします。

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
于 2010-01-18T18:05:30.643 に答える
2

この質問が出されてから何年も経ちますが、探しxhr.responseTextていた答えはまだ見つかりません。次の形式で文字列が返されました。

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

これは絶対にユーザーに見せたくありません。私が探していたのは、以下のようなものです:

alert(xhr.responseJSON.message);

xhr.responseJSON.messageユーザーに表示できるJsonオブジェクトからの正確なメッセージを教えてくれます。

于 2016-06-24T02:05:45.150 に答える
0

まず、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

于 2012-05-09T08:41:26.390 に答える
0

私の場合、コントローラーから 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));
    }
于 2020-10-06T05:24:08.017 に答える