Can I return custom error from JsonResult to jQuery ajax error method?

前端 未结 5 2035
温柔的废话
温柔的废话 2020-12-07 16:06

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if n

相关标签:
5条回答
  • 2020-12-07 16:27

    The advice above wouldn't work on IIS for remote clients. They will receive a standard error page like 500.htm instead of a response with a message. You have to use customError mode in web.config, or add

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

    or

    "You can also go into IIS manager --> Error Pages then click on the right on "Edit feature settings..." And set the option to "Detailed errors" then it will be your application that process the error and not IIS."

    0 讨论(0)
  • 2020-12-07 16:29

    You could write a custom error filter:

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

    and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.

    And on the client:

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

    Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:

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

    and then:

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

    Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.

    0 讨论(0)
  • 2020-12-07 16:29

    If for some reason you can't send a server error. Here's an option that you can do.

    server side

     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;
    

    client side

     $.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....================="); }
            });
    
    0 讨论(0)
  • 2020-12-07 16:36

    My MVC project wasn't returning any error message (custom or otherwise). I found that this worked well for me:

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

    Showing the xhr.responseText resulted in a very detailed HTML formatted alert message.

    0 讨论(0)
  • 2020-12-07 16:44

    you can return JsonResult with error and track the status at javascript side to show error message :

     JsonResult jsonOutput = null;
            try
            {
               // do Stuff
            }
            catch
            {
                jsonOutput = Json(
                     new
                     {
                         reply = new
                         {
                             status = "Failed",
                             message = "Custom message "
                         }
                     });
            }
            return jsonOutput ;
    
    0 讨论(0)
提交回复
热议问题