ASP.NET MVC Ajax 오류 처리
jquery ajax가 작업을 호출할 때 컨트롤러에 느려진 예외를 처리하려면 어떻게 해야 합니까?
예를 들어 디버깅 모드일 경우 예외 메시지를 표시하거나 일반 오류 메시지만 표시하는 Ajax 호출 중에 모든 종류의 서버 예외에서 실행되는 글로벌 자바스크립트 코드를 원합니다.
클라이언트 측에서 Ajax 오류에 대한 함수를 호출하겠습니다.
서버 측에서는 사용자 지정 작업 필터를 작성해야 합니까?
서버가 200과 다른 상태 코드를 보내면 오류 콜백이 실행됩니다.
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
글로벌 오류 처리기를 등록하려면 다음 방법을 사용할 수 있습니다.
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
또 다른 방법은 JSON을 사용하는 것입니다.따라서 서버에서 예외를 포착하여 JSON 응답으로 변환하는 사용자 지정 작업 필터를 작성할 수 있습니다.
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
다음 속성으로 컨트롤러 작업을 장식합니다.
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
마지막으로 호출합니다.
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});
Google을 검색한 후 MVC Action Filter를 기반으로 간단한 예외 처리를 작성합니다.
public class HandleExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
filterContext.Exception.StackTrace
}
};
filterContext.ExceptionHandled = true;
}
else
{
base.OnException(filterContext);
}
}
}
global.svx:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionAttribute());
}
레이아웃 또는 마스터 페이지에 다음 스크립트를 작성합니다.
<script type="text/javascript">
$(document).ajaxError(function (e, jqxhr, settings, exception) {
e.stopPropagation();
if (jqxhr != null)
alert(jqxhr.responseText);
});
</script>
마지막으로 당신은 커스텀 에러를 켜고 즐겨야 합니다 :)
불행하게도, 두 대답 모두 저에게 좋지 않습니다.놀랍게도 해결책은 훨씬 더 간단합니다.컨트롤러에서 반환:
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);
그리고 원하는 대로 클라이언트에서 표준 HTTP 오류로 처리합니다.
시간이 부족해서 빠른 해결을 했고 잘 작동했습니다.더 나은 옵션은 예외 필터를 사용하는 것이지만, 간단한 솔루션이 필요한 경우에는 제 솔루션이 도움이 될 수도 있습니다.
저는 다음과 같이 했습니다.컨트롤러 방법에서 데이터 내부에 "Success" 속성이 있는 JsonResult를 반환했습니다.
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
나중에 Ajax 통화에서 예외가 있는지 확인하기 위해 이 속성을 요청했습니다.
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
이게 도움이 되길 바랍니다.해피 코드! :P
알레호의 반응에 동의하여 여기 완전한 예가 있습니다.그것은 매력적으로 작용하고 매우 간단합니다.
컨트롤러 코드
[HttpGet]
public async Task<ActionResult> ChildItems()
{
var client = TranslationDataHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("childItems);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
return Json(content, JsonRequestBehavior.AllowGet);
}
else
{
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
}
}
보기의 Javascript 코드
var url = '@Html.Raw(@Url.Action("ChildItems", "WorkflowItemModal")';
$.ajax({
type: "GET",
dataType: "json",
url: url,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Do something with the returned data
},
error: function (xhr, status, error) {
// Handle the error.
}
});
이것이 다른 누군가에게 도움이 되기를 바랍니다!
클라이언트 측의 Ajax 호출에서 발생한 오류를 처리하기 위해 다음에 함수를 할당합니다.error
Ajax 호출 옵션입니다.
기본값을 전체적으로 설정하려면 여기에 설명된 기능 http://api.jquery.com/jQuery.ajaxSetup 을 사용할 수 있습니다.
언급URL : https://stackoverflow.com/questions/4707755/asp-net-mvc-ajax-error-handling
'programing' 카테고리의 다른 글
Powershell 내에서 폴더를 여는 방법 (0) | 2023.08.30 |
---|---|
Swift 프로그램에서 자동 해제 풀을 사용해야 합니까? (0) | 2023.08.30 |
각도 단위 테스트 입력 값 (0) | 2023.08.30 |
텔레릭을 사용하여 Excel(XLSX)로 내보낼 때 컬렉션을 해석하는 방법은 무엇입니까? (0) | 2023.08.30 |
jquery $(this).id가 정의되지 않음을 반환합니다. (0) | 2023.08.30 |