asp.net mvc 응용 프로그램에서 오류를 처리하기 위해 CustomErrorHandler 특성을 사용하고 있습니다. 코드는 다음과 같습니다 :asp.net MVC 3.0의 경우 JSON 오류 응답을 표시하는 방법 MVC 3.0 App의 Ajax
public class CustomHandleErrorAttribute : HandleErrorAttribute // Error handler
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
{
return;
}
if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
{
return;
}
// if the request is AJAX return JSON else view.
if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
}
else
{
filterContext.ExceptionHandled = true;
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = View,
MasterName = Master,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
}
}
protected JsonResult AjaxError(string message, ExceptionContext filterContext)
{
if (String.IsNullOrEmpty(message))
message = "Something went wrong while processing your request. Please refresh the page and try again.";
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
return new JsonResult { Data = new { ErrorMessage = message }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
일반 오류와 Ajax 오류를 모두 포착 할 수 있습니다.
정상 오류가 발생하는 경우, 내가 아약스 오류의 경우, 오류 모델을 구축하고 오류보기
를 표시하지만하고, 내가 JSON의 형태로 오류 메시지를 보여주고 싶다. 이 data.ErrorMessage에 대한 정의되지 않은 말 대신 실제 오류 메시지가 표시되고,function Failed(data) { // Onfailed call of MVC Ajax form
alert("Sorry,An error occured while processing your request");
alert(data.ErrorMessage);
}
그러나 :
내가 좋아하는 어떤 것을 시도했다.처리 방법에 대한 도움/제안 바랍니다.
Updated2는 :이가 해결 됐는지입니다 : 제대로 return 문을 형성하지 않는 것 같은
function Failed(jqXHR, textStatus, errorThrown) {
var Error = $.parseJSON(jqXHR.responseText);
alert("Sorry,An error occured while processing your request");
alert(Error.ErrorMessage);
}
@ Oleg .. 나는 Jquery unobstrusive ajax를 사용하고 있습니다 .. –
@ Oleg..it는 실패한 함수입니다.하지만 오류 정보를 가져올 수 없습니다. –
@Avinash :'data.ErrorMessage'를 사용합니다 (게시 한 코드 참조). 대신에'$ .parseJSON (data.responseText) .ErrorMessage' (내 대답 참조)를 사용해야합니다. – Oleg