program tip

jQuery Ajax 오류 처리, 사용자 정의 예외 메시지 표시

radiobox 2020. 9. 30. 09:11
반응형

jQuery Ajax 오류 처리, 사용자 정의 예외 메시지 표시


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

두 번째 경고에서 발생한 오류를 경고하면 표시 undefined되고 상태 코드는 500입니다.

내가 어디로 잘못 가고 있는지 잘 모르겠습니다. 이 문제를 해결하려면 어떻게해야합니까?


Response.StatusCode200이 아닌 다른 값으로 설정했는지 확인하십시오.를 사용하여 예외 메시지를 작성한 Response.Write다음 ...

xhr.responseText

.. 자바 스크립트에서.


제어 장치:

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 년에 답변을 받으면 jQuery 3.0에서 더 이상 사용되지 않는 .fail()오류 처리 .error()에 사용하십시오.

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

도움이 되길 바랍니다


일반 / 재사용 가능한 솔루션

이 답변은이 문제에 부딪히는 모든 사람들에 대한 향후 참조를 위해 제공됩니다. 솔루션은 다음 두 가지로 구성됩니다.

  1. ModelStateException서버에서 유효성 검사가 실패 할 때 throw되는 사용자 지정 예외 (데이터 주석을 사용하고 강력한 형식의 컨트롤러 작업 매개 변수를 사용할 때 모델 상태가 유효성 검사 오류를보고 함)
  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 (response) {
      var r = jQuery.parseJSON(response.responseText);
      alert("Message: " + r.Message);
      alert("StackTrace: " + r.StackTrace);
      alert("ExceptionType: " + r.ExceptionType);
}

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

}


이는 아마도 따옴표가없는 JSON 필드 이름 때문일 수 있습니다.

다음에서 JSON 구조를 변경합니다.

{welcome:"Welcome"}

에:

{"welcome":"Welcome"}

Ajax 응답 처리기가 HTTP 상태 코드를 사용하여 오류가 있는지 확인한다고 생각합니다.

따라서 서버 측 코드에서 Java 예외를 던지지 만 HTTP 응답에 500 상태 코드가없는 경우 jQuery (또는이 경우 XMLHttpRequest 객체)는 모든 것이 정상이라고 가정합니다.

ASP.NET에서 ArgumentException ( "Do n'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); }
});

xhr 개체에 throw 된 예외의 JSON 개체가 있습니다. 그냥 사용

alert(xhr.responseJSON.Message);

JSON 객체는 'ExceptionType'및 'StackTrace'의 두 가지 다른 속성을 노출합니다.


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

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.


$("#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({...

... ... });


First we need to set <serviceDebug includeExceptionDetailInFaults="True" /> in web.config:

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

In addition to that at jquery level in error part you need to parse error response that contains exception like:

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

Then using r.Message you can actully show exception text.

Check complete code: http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html


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.

참고URL : https://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages

반응형