복붙노트

[JQUERY] jQuery를 아약스 오류 처리, 쇼 사용자 정의 예외 메시지

JQUERY

jQuery를 아약스 오류 처리, 쇼 사용자 정의 예외 메시지

해결법


  1. 1.다음 사용 Response.Write를 사용하여 200 쓰기하여 예외의 메시지가 아닌 다른 무언가에 반드시있는 거 설정 Response.StatusCode합니다 ...

    다음 사용 Response.Write를 사용하여 200 쓰기하여 예외의 메시지가 아닌 다른 무언가에 반드시있는 거 설정 Response.StatusCode합니다 ...

    xhr.responseText
    

    자바 스크립트를 것 말이다.


  2. 2.제어 장치:

    제어 장치:

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

  3. 3.서버 측:

    서버 측:

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

    일반 아약스 오류 처리

    나는 모든 아약스 요청을 처리하는 몇 가지 일반적인 오류를해야합니다. 나는 ajaxError 핸들러를 설정하고 HTML 내용의 상단에 사업부라는 이름의 errorcontainer에 오류가 표시됩니다.

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

  4. 4.당신은 JSON에에서 responseText를 변환해야합니다. jQuery를 사용하여 :

    당신은 JSON에에서 responseText를 변환해야합니다. jQuery를 사용하여 :

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

  5. 5.asp.net를 호출하는 경우이 오류 메시지의 제목을 반환합니다 :

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

  6. 6.이것은 내가 무슨 짓을 그리고 그것은 MVC 5 응용 프로그램에서 지금까지 작동합니다.

    이것은 내가 무슨 짓을 그리고 그것은 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({
        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;
        }
    });
    

  7. 7.누군가가 ()에는 .error로 오류 처리에 대한 대답, 사용 .fail ()에 대한 2016에서 여기 경우 jQuery를 3.0로 사용되지 않습니다

    누군가가 ()에는 .error로 오류 처리에 대한 대답, 사용 .fail ()에 대한 2016에서 여기 경우 jQuery를 3.0로 사용되지 않습니다

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

    나는 그것이 도움이되기를 바랍니다


  8. 8.이 답변이 문제에 부딪 모든 사람들에게 미래 참조 용으로 만 제공됩니다. 해결 방법은 두 가지로 구성된다 :

    이 답변이 문제에 부딪 모든 사람들에게 미래 참조 용으로 만 제공됩니다. 해결 방법은 두 가지로 구성된다 :

    jQuery를 아약스 성공 및 오류 핸들러 자신의 잠재력을 사용하는 호출이 최적의 인프라를 제공합니다.

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

    전체 문제는 응용 프로그램에서이 작업을 실행하는 모든 코드를 찾을 수있는이 블로그 게시물에 자세히 설명되어 있습니다.


  9. 9.난 내가 서버에서 전송 된 메시지를 구문 분석하고 스택 트레이스없이 사용자에게 친근한 메시지를 표시 할 수 있기 때문에이 좋은 것으로 판명 ...

    난 내가 서버에서 전송 된 메시지를 구문 분석하고 스택 트레이스없이 사용자에게 친근한 메시지를 표시 할 수 있기 때문에이 좋은 것으로 판명 ...

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

  10. 10.오류 : 함수 (XHR, ajaxOptions, thrownError) { 경고 (xhr.status); 경고 (thrownError); } 캐치 오류 코드 오류 아약스 요청에서 서버에 클라이언트를 연결 당신은 성공의 범위에서 응용 프로그램의 전송의 표시 오류 메시지를 원하는 경우

    오류 : 함수 (XHR, ajaxOptions, thrownError) { 경고 (xhr.status); 경고 (thrownError); } 캐치 오류 코드 오류 아약스 요청에서 서버에 클라이언트를 연결 당신은 성공의 범위에서 응용 프로그램의 전송의 표시 오류 메시지를 원하는 경우

    성공 : 기능 (데이터) { // 데이터 객체 전송 형태의 서버입니다 // 데이터의 특성 // 상태 유형 부울 // MSG 타입의 캐릭터 라인 // 결과 형 문자열 (data.status) {// 사실이 아니다 오류가있는 경우 $ ( '#의 api_text') 발 (data.result).; } 그밖에 { $ ( '#의 ERROR_TEXT') 발 (data.msg).; } }


  11. 11.이것은 아마 인용 부호를 가지고하지 JSON 필드 이름에 의해 발생합니다.

    이것은 아마 인용 부호를 가지고하지 JSON 필드 이름에 의해 발생합니다.

    json으로 구조에서 변경 :

    {welcome:"Welcome"}
    

    에:

    {"welcome":"Welcome"}
    

  12. 12.당신은 XHR 객체에 던져 예외의 JSON 객체를 가지고있다. 그냥 사용

    당신은 XHR 객체에 던져 예외의 JSON 객체를 가지고있다. 그냥 사용

    alert(xhr.responseJSON.Message);
    

    json으로 개체는 다른 두 속성을 노출 '예외 유형'과 '스택 트레이스를'


  13. 13.이 기능은 기본적으로 고유 한 임의 API 키의와 경우에 그 다음 팝업하지 않는 경우 오류 메시지가 나타납니다와 대화 상자를 생성

    이 기능은 기본적으로 고유 한 임의 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));
    }
    

    부하 () 메소드가 완료되면 선택적 콜백 파라미터를 지정하는 콜백 함수를 실행한다. 콜백 함수는 다른 매개 변수를 가질 수 있습니다 :

    요청이 실패하면 함수가 호출된다. 함수는 세 개의 인자 수신 다음 jqXHR을 (jQuery를 1.4.x로에서 XMLHttpRequest 객체) 객체 하나가 발생한 경우 발생한 오류의 유형 및 임의의 예외 객체를 기술하는 문자열. (NULL) 이외의 두 번째 인수에 사용할 수있는 값은 "중단", "타임 아웃", "오류", 및 "parsererror"입니다. HTTP 오류가 발생하면, errorThrown는 "찾을 수 없음"또는, HTTP 상태의 텍스트 부분을 받아 "내부 서버 오류가 발생했습니다." jQuery를 1.5로, 오류 설정 기능의 배열을 받아 들일 수 있습니다. 각 기능을 차례로 호출됩니다. 참고 :이 핸들러는 크로스 도메인 스크립트와 크로스 도메인 JSONP 요청에 대해 호출되지 않습니다.


  14. 14.나는 Ajax 응답 핸들러는 에러가 발생했을 경우 확인하기 위해 HTTP 상태 코드를 사용 믿습니다.

    나는 Ajax 응답 핸들러는 에러가 발생했을 경우 확인하기 위해 HTTP 상태 코드를 사용 믿습니다.

    그래서 당신은 당신의 서버 측 코드에서 자바 예외를 던져하지만 HTTP 응답은 500 상태 코드 jQuery를 (또는이 경우에 아마는 XMLHttpRequest 객체)가없는 단지 모든 것이 괜찮다고 생각합니다.

    나는이 ArgumentException이 같은 것을 던지고 ASP.NET에서 비슷한 문제가 있었다 때문에 ( "... 어떻게 해야할지하지 않음")이 말하고 있지만 오류 핸들러는 발사되지 않았다.

    나는 500 또는 I 오류가 있었다 여부 (200) 중 하나에 Response.StatusCode을 설정합니다.


  15. 15.jQuery.parseJSON 성공 및 오류 유용합니다.

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

  16. 16.

    $("#save").click(function(){
        $("#save").ajaxError(function(event,xhr,settings,error){
            $(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url);
        });
    });
    

  17. 17.사용하여 서버에 새 예외를 던져 :

    사용하여 서버에 새 예외를 던져 :

    Response.StatusCode = 500

    Response.StatusDescription = ex.Message ()

    나는 상태 설명은 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
    

  18. 18.이 질문에 질문이기 때문에 몇 년되었지만, 나는 여전히 내가 찾던 해답으로 xhr.responseText를 찾을 수 없습니다. 그것은 다음과 같은 형식으로 나에게 문자열을 반환

    이 질문에 질문이기 때문에 몇 년되었지만, 나는 여전히 내가 찾던 해답으로 xhr.responseText를 찾을 수 없습니다. 그것은 다음과 같은 형식으로 나에게 문자열을 반환

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

    이는 확실히 사용자에게 보여주고 싶지 않아요. 내가 무엇을 찾고 있었 아래 같은 것입니다 :

    alert(xhr.responseJSON.message);
    

    xhr.responseJSON.message는 나에게 사용자에게 표시 할 수있는 JSON 객체에서 정확한 메시지를 제공합니다.


  19. 19.

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

    ... ... });


  20. 20.처음에 우리는 설정해야합니다 Web.config의에서 :

    처음에 우리는 설정해야합니다 Web.config의에서 :

    <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

  21. from https://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages by cc-by-sa and MIT license