jQuery Ajax error handling, show custom exception messages

前端 未结 21 2806
滥情空心
滥情空心 2020-11-22 01:50

Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?

For example, if I want to throw an exception on the server side v

21条回答
  •  青春惊慌失措
    2020-11-22 02:27

    Controller:

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

    View script:

    $.ajax({
        type: "post", url: "/SomeController/SomeAction",
        success: function (data, text) {
            //...
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    });
    

提交回复
热议问题