source

JsonResult에서 jQuery ajax 오류 메서드로 사용자 지정 오류를 반환할 수 있습니까?

myloves 2023. 2. 27. 21:55

JsonResult에서 jQuery ajax 오류 메서드로 사용자 지정 오류를 반환할 수 있습니까?

ASP에서 커스텀에러 정보를 전달하려면 어떻게 해야 하나요?넷 MVC3JsonResult에의 메서드error(또는success또는complete필요한 경우)의 기능jQuery.ajax()이상적으로는 다음을 실현하고 싶다.

  • 그래도 서버에 오류 발생(로그에 사용됨)
  • 클라이언트에서 오류에 대한 사용자 지정 정보 검색

다음은 내 코드의 기본 버전입니다.

컨트롤러 Json Result 메서드

public JsonResult DoStuff(string argString)
{
    string errorInfo = "";

    try
    {
        DoOtherStuff(argString);
    }
    catch(Exception e)
    {
        errorInfo = "Failed to call DoOtherStuff()";
        //Edit HTTP Response here to include 'errorInfo' ?
        throw e;
    }

    return Json(true);
}

자바스크립트

$.ajax({
    type: "POST",
    url: "../MyController/DoStuff",
    data: {argString: "arg string"},
    dataType: "json",
    traditional: true,
    success: function(data, statusCode, xhr){
        if (data === true)
            //Success handling
        else
            //Error handling here? But error still needs to be thrown on server...
    },
    error: function(xhr, errorType, exception) {
        //Here 'exception' is 'Internal Server Error'
        //Haven't had luck editing the Response on the server to pass something here
    }
});

내가 시도했던 것(잘 안 된 것):

  • 에서 오류 정보를 반환하는 중catch블록
    • 이 방법은 작동하지만 예외를 발생시킬 수 없습니다.
  • 에서 HTTP 응답 편집catch블록
    • 그 후 검사했다.xhrjQuery 오류 핸들러에서
    • xhr.getResponseHeader(), 등에는 디폴트 ASP가 포함되어 있습니다.NET 에러 페이지가 표시되지만, 내 정보가 없습니다.
    • 그럴 수도 있을 것 같은데 제가 잘못했어요?

커스텀 에러 필터를 작성할 수 있습니다.

public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.ExceptionHandled = true;
            filterContext.Result = new JsonResult
            {
                Data = new
                {
                    // obviously here you could include whatever information you want about the exception
                    // for example if you have some custom exceptions you could test
                    // the type of the actual exception and extract additional data
                    // For the sake of simplicity let's suppose that we want to
                    // send only the exception message to the client
                    errorMessage = filterContext.Exception.Message
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }
}

그런 다음 글로벌필터로 등록하거나 AJAX를 사용하여 호출하는 특정 컨트롤러 또는 액션에만 적용됩니다.

그리고 클라이언트:

$.ajax({
    type: "POST",
    url: "@Url.Action("DoStuff", "My")",
    data: { argString: "arg string" },
    dataType: "json",
    traditional: true,
    success: function(data) {
        //Success handling
    },
    error: function(xhr) {
        try {
            // a try/catch is recommended as the error handler
            // could occur in many events and there might not be
            // a JSON response from the server
            var json = $.parseJSON(xhr.responseText);
            alert(json.errorMessage);
        } catch(e) { 
            alert('something bad happened');
        }
    }
});

각 AJAX 요청에 대해 반복적인 오류 처리 코드를 쓰는 것이 빠르게 지루해질 수 있으므로 페이지에 있는 모든 AJAX 요청에 대해 한 번 쓰는 것이 좋습니다.

$(document).ajaxError(function (evt, xhr) {
    try {
        var json = $.parseJSON(xhr.responseText);
        alert(json.errorMessage);
    } catch (e) { 
        alert('something bad happened');
    }
});

그 후:

$.ajax({
    type: "POST",
    url: "@Url.Action("DoStuff", "My")",
    data: { argString: "arg string" },
    dataType: "json",
    traditional: true,
    success: function(data) {
        //Success handling
    }
});

다른 방법은 제가 제시한 글로벌 예외 핸들러를 조정하여 ErrorController 내에서 AJAX 요청 여부를 확인하고 예외 세부사항을 JSON으로 반환하는 것입니다.

위의 조언은 원격 클라이언트의 IIS에서는 작동하지 않습니다.메시지 응답 대신 500.htm과 같은 표준 오류 페이지가 나타납니다.web.config에서 customError 모드를 사용하거나

<system.webServer>
        <httpErrors existingResponse="PassThrough" />
    </system.webServer>

또는

「IIS 매니저 --> 에러 페이지에 액세스 해, 「기능 설정의 편집」의 오른쪽을 클릭할 수도 있습니다.「Detailed errors(상세 에러)」옵션을 설정하면, 그 에러를 처리하는 것은, IIS 가 아니고, 사용의 애플리케이션입니다.

오류와 함께 JsonResult를 반환하고 javascript 측에서 상태를 추적하여 오류 메시지를 표시할 수 있습니다.

 JsonResult jsonOutput = null;
        try
        {
           // do Stuff
        }
        catch
        {
            jsonOutput = Json(
                 new
                 {
                     reply = new
                     {
                         status = "Failed",
                         message = "Custom message "
                     }
                 });
        }
        return jsonOutput ;

MVC 프로젝트에서 오류 메시지(커스텀 또는 기타)를 반환하지 않았습니다.이것은 나에게 있어서 잘 기능하고 있는 것을 알았다.

$.ajax({
        url: '/SomePath/Create',
        data: JSON.stringify(salesmain),
        type: 'POST',
        contentType: 'application/json;',
        dataType: 'json',
        success: function (result) {

            alert("start JSON");
            if (result.Success == "1") {
                window.location.href = "/SomePath/index";
            }
            else {
                alert(result.ex);
            }

            alert("end JSON");
        },
        error: function (xhr) {

            alert(xhr.responseText);

        }
        //error: AjaxFailed
    });

xhr.responseText를 표시하면 HTML 형식의 매우 상세한 경보메시지가 표시됩니다.

어떤 이유로 서버 에러를 송신할 수 없는 경우.여기 당신이 할 수 있는 옵션이 있습니다.

서버측

 var items = Newtonsoft.Json.JsonConvert.DeserializeObject<SubCat>(data); // Returning a parse object or complete object

        if (!String.IsNullOrEmpty(items.OldName))
        {
            DataTable update = Access.update_SubCategories_ByBrand_andCategory_andLikeSubCategories_BY_PRODUCTNAME(items.OldName, items.Name, items.Description);

            if(update.Rows.Count > 0)
            {
                List<errors> errors_ = new List<errors>();
                errors_.Add(new errors(update.Rows[0]["ErrorMessage"].ToString(), "Duplicate Field", true));

                return Newtonsoft.Json.JsonConvert.SerializeObject(errors_[0]); // returning a stringify object which equals a string | noncomplete object
            }

        }

        return items;

클라이언트 측

 $.ajax({
            method: 'POST',
            url: `legacy.aspx/${place}`,
            contentType: 'application/json',
            data:  JSON.stringify({data_}),              
            headers: {
                'Accept': 'application/json, text/plain, *',
                'Content-type': 'application/json',
                'dataType': 'json'
            },
            success: function (data) {

                if (typeof data.d === 'object') { //If data returns an object then its a success

                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 3000
                    })

                    Toast.fire({
                        type: 'success',
                        title: 'Information Saved Successfully'
                    })

                    editChange(place, data.d, data_);

                } else { // If data returns a stringify object or string then it failed and run error

                    var myData = JSON.parse(data.d);

                    Swal.fire({
                      type: 'error',
                      title: 'Oops...',
                      text: 'Something went wrong!',
                      footer: `<a href='javascript:showError("${myData.errorMessage}", "${myData.type}", ${data_})'>Why do I have this issue?</a>`
                    })
                }
            },
            error: function (error) { console.log("FAIL....================="); }
        });

언급URL : https://stackoverflow.com/questions/9298466/can-i-return-custom-error-from-jsonresult-to-jquery-ajax-error-method