在MVC中,为什么HandleError(扩展与否)或Application_Error没有捕获SqlExceptions?
public override void OnException(ExceptionContext filterContext)
{
int httpcode = new HttpException(null, filterContext.Exception).GetHttpCode();
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
return;
if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
return;
var er = new OEB.DataAccess.ErrorHandlerRepository();
er.LogException("Custom - " + filterContext.Exception.ToString());
filterContext.ExceptionHandled = true;
switch (httpcode)
{
case 404:
filterContext.Result = new RedirectResult("~/ErrorHandler/NotFound");
break;
case 500:
filterContext.Result = new RedirectResult("~/ErrorHandler/ServerError");
break;
default:
filterContext.Result = new RedirectResult("~/ErrorHandler/General");
break;
}
}
我在Filter.Config中注册了这个:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomErrorHandlerAttribute());
}
}
我正在使用Dapper,并尝试从无效插入中捕获SQLException(AspNetRoles2不存在),并获得正常的黄色屏幕:
public bool CreateRole(string roleName)
{
int rowsAffected = Execute("INSERT into AspNetRoles2 (RoleName) VALUES (@roleName)", new { roleName = roleName });
return rowsAffected == 1 ? true : false;
}
protected int Execute(string sp, object parameters = null)
{
using (var scope = new TransactionScope())
{
using (var conn = new SqlConnection(secConnStr))
{
rowsAffectedCount = conn.Execute(sp, parameters);
}
scope.Complete();
}
}