使用异常过滤器在不中断页面的情况下显示自定义消息
Show custom message without breaking page using exception filter
我正在使用一个 MVC 应用程序,我必须在其中处理代码中发生的所有异常。我发现了异常过滤器并在那里实现了。下面是创建的异常过滤器代码:
public class HandleException : HandleErrorAttribute
{
#region Log Initialization
FileLogService logService = new
FileLogService(typeof(HandleException));
#endregion
public override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
Log(filterContext.Exception);
base.OnException(filterContext);
}
private void Log(Exception exception)
{
logService.Error(exception.ToString());
}
}
现在我在我的控制器中使用这个过滤器作为属性,如下所示:
[AuthSession]
[HandleException]
public class OrganizationalController : BaseController
{
public ActionResult OrgSummary()
{
try
{
int a = 1, b = 0;
int result = a / b;
}
catch (Exception ex)
{
throw ex;
}
ViewData["ShowGrid"] = false;
return View();
}
}
正如您在上面的代码中看到的,我试图在代码中生成异常。在 catch 异常块中,当我使用 throw 关键字时,异常过滤器将被执行,否则不会。
现在我需要在应用程序发生任何异常时为用户显示自定义弹出消息。在弹出消息中,一旦用户单击确定按钮,用户就应该在同一页面上可用。页面不应中断或空白。
我如何实现这个功能?
试试这个代码。可能有帮助
public class MyExceptionFilter: FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// below code will redirect to the error view
filterContext.Result = new RedirectResult("ErrorPage.html");
filterContext.ExceptionHandled = true;
}
}
然后您需要将以上内容作为属性应用到您的操作方法中,例如:
[MyExceptionFilter]<br>
public 动作结果 XYZ()
{
}
我正在使用一个 MVC 应用程序,我必须在其中处理代码中发生的所有异常。我发现了异常过滤器并在那里实现了。下面是创建的异常过滤器代码:
public class HandleException : HandleErrorAttribute
{
#region Log Initialization
FileLogService logService = new
FileLogService(typeof(HandleException));
#endregion
public override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
Log(filterContext.Exception);
base.OnException(filterContext);
}
private void Log(Exception exception)
{
logService.Error(exception.ToString());
}
}
现在我在我的控制器中使用这个过滤器作为属性,如下所示:
[AuthSession]
[HandleException]
public class OrganizationalController : BaseController
{
public ActionResult OrgSummary()
{
try
{
int a = 1, b = 0;
int result = a / b;
}
catch (Exception ex)
{
throw ex;
}
ViewData["ShowGrid"] = false;
return View();
}
}
正如您在上面的代码中看到的,我试图在代码中生成异常。在 catch 异常块中,当我使用 throw 关键字时,异常过滤器将被执行,否则不会。
现在我需要在应用程序发生任何异常时为用户显示自定义弹出消息。在弹出消息中,一旦用户单击确定按钮,用户就应该在同一页面上可用。页面不应中断或空白。
我如何实现这个功能?
试试这个代码。可能有帮助
public class MyExceptionFilter: FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// below code will redirect to the error view
filterContext.Result = new RedirectResult("ErrorPage.html");
filterContext.ExceptionHandled = true;
}
}
然后您需要将以上内容作为属性应用到您的操作方法中,例如:
[MyExceptionFilter]<br>
public 动作结果 XYZ()
{
}