ASP.NET Core 2.2 MVC 앱에서 오류 처리를 설정하고 있습니다. 개발 환경에서는 app.UseDeveloperExceptionPage();
, 및 프로덕션에서 app.UseExceptionHandler("/Error/Index");
. 환경에 따라 비 AJAX (정규 양식 제출) 요청 중에 올바른 오류 페이지로 이동합니다.
AJAX 요청 중에 서버에서 예외가 발생하면 앱이 환경에 따라 올바른 오류 페이지를 표시하도록하고 싶습니다.
아래 코드 예제에서 볼 수 있듯이 위에서 설명한 모든 내용을 이미 설정했습니다.
이것이 작동하는 동안 (아직 InitializeGlobalAjaxEventHandlers
기능 에서 TODO를 완료해야하지만 ) 몇 가지 우려가 있습니다.
비 AJAX는 MVC에서 호출와 "공식 / 올바른"와 함께 할 수있는 방법이처럼 느낀다 app.UseDeveloperExceptionPage();
및 app.UseExceptionHandler("/Error/Index");
자동 오류 페이지에 프로그램을 리디렉션합니다. 그러나 AJAX가 오류 처리를 끝내면 내가 조사한 다른 솔루션의 부품과 함께 결합했기 때문에 자신감이 없습니다. 무엇이 잘못 될 수 있는지 모를까 걱정됩니다.
MVC에서 AJAX 요청 중에 오류를 처리하는 적절한 방법입니까? 이 설정에 문제가 생길 수 있습니까? 이것은 부적절하거나 일반적인 표준과 너무 멀리 떨어져 있습니까?
Startup.cs> 구성 방법 :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//using build config to use the correct error page: https://stackoverflow.com/a/62177235/12300287
//Reason why we don't use environmental variables is because we can't guarantee access to clients'
//machines to create them.
#if (DEVELOPMENT || STAGING)
app.UseDeveloperExceptionPage();
#else
app.UseExceptionHandler("/Error/Index");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
#endif
app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=UserAccess}/{action=Index}/{id?}");
});
}
ErrorController.cs :
public class ErrorController : Controller
{
[AllowAnonymous]
public IActionResult Index()
{
IExceptionHandlerPathFeature exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
Exception exception = exceptionDetails?.Error; // Here will be the exception details.
Error model = new Error();
model.ID = exception.HResult;
model.Message = exception.Message;
model.Path = exceptionDetails.Path;
return View(model);
}
}
글로벌 AJAX 오류 이벤트 핸들러 ( if
인증을 처리 하는 명령문) :
function InitializeGlobalAjaxEventHandlers() {
$(document).ajaxError(function (event, xhr, ajaxSettings, thrownError) {
//status is set in the [AuthorizeAjax] action filter if user isn't authenticated
if (xhr.status == 403) {
var response = $.parseJSON(xhr.responseText);
window.location = response.redirectUrl;
}
//the document HTML is replaces by responseText value, which contains the HTML of error page
document.write(xhr.responseText);
//TODO: will need to display an error page if responseText is empty, which
//can happen if an AJAX request doesn't reach the server (for example: if URL is incorrect).
});
}
설명했듯이 고려해야 할 두 가지 코드 스레드가 있습니다. 하나는 클라이언트에 있고 다른 하나는 서버에 있습니다.
서버는 예상치 못한 결과에 대한 코드와 메시지를 반환 할 수 있지만 클라이언트는 여전히 견고하고 독립형이어야합니다. 예를 들어 서버에 도달 할 수없는 경우 처리해야하는 클라이언트에서 시간 초과 오류가 발생할 수 있습니다. 위에서 언급했듯이 로컬 및 글로벌 Ajax 수준에서 오류를 포착 할 수 있습니다.
서버는 클라이언트에 도달하지 않는 오류 응답을 생성 할 수도 있습니다.
일부 프로젝트에서 다음을 수행했습니다.-서버에서 예상치 못한 결과가 생성되면 데이터베이스에 기록되고 JSON 메시지가 오류로 반환됩니다.
클라이언트에서 예상치 못한 결과가 생성되면 서버 서비스가 호출되어 데이터베이스에 오류를 기록합니다.
두 경우 모두 현재 페이지에 메시지가 표시됩니다. 사용자는 최근 오류 (데이터베이스에 저장 됨)가 표시되는 오류 페이지로 이동할 수도 있습니다.
다양한 크기의 많은 프로젝트에서 작업하면서 실제로 모든 것에 맞는 솔루션이 없다는 결론에 도달했습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다