Custom Error Handling

This commit is contained in:
Gary Sharp
2013-11-11 17:04:04 +11:00
parent a63041abf2
commit 1cbbf1dde4
12 changed files with 296 additions and 49 deletions
+28 -3
View File
@@ -77,8 +77,30 @@
<Reference Include="System.IO.Compression" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.Helpers.dll</HintPath>
</Reference>
<Reference Include="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.AspNet.Mvc.4.0.30506.0\lib\net40\System.Web.Mvc.dll</HintPath>
</Reference>
<Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.AspNet.Razor.2.0.30506.0\lib\net40\System.Web.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.Deployment.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
@@ -195,12 +217,15 @@
<Compile Include="Users\UserService.cs" />
<Compile Include="Web\AuthorizedController.cs" />
<Compile Include="Web\AuthorizedDatabaseController.cs" />
<Compile Include="Web\BaseController.cs" />
<Compile Include="Web\Bundles\Bundle.cs" />
<Compile Include="Web\Bundles\BundleExtensions.cs" />
<Compile Include="Web\Bundles\BundleHandler.cs" />
<Compile Include="Web\Bundles\BundleModule.cs" />
<Compile Include="Web\Bundles\BundleTable.cs" />
<Compile Include="Web\DatabaseController.cs" />
<Compile Include="Web\HandleErrorAttribute.cs" />
<Compile Include="Web\HelperExtensions.cs" />
<Compile Include="Web\WebViewPage.cs" />
</ItemGroup>
<ItemGroup>
@@ -228,7 +253,7 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<ProjectExtensions>
<VisualStudio>
<UserProperties BuildVersion_UpdateFileVersion="True" BuildVersion_UpdateAssemblyVersion="True" BuildVersion_BuildVersioningStyle="None.DeltaBaseYear.MonthAndDayStamp.TimeStamp" BuildVersion_StartDate="2011/7/1" BuildVersion_BuildAction="Both" BuildVersion_DetectChanges="False" BuildVersion_UseGlobalSettings="False" />
<UserProperties BuildVersion_UseGlobalSettings="False" BuildVersion_DetectChanges="False" BuildVersion_BuildAction="Both" BuildVersion_StartDate="2011/7/1" BuildVersion_BuildVersioningStyle="None.DeltaBaseYear.MonthAndDayStamp.TimeStamp" BuildVersion_UpdateAssemblyVersion="True" BuildVersion_UpdateFileVersion="True" />
</VisualStudio>
</ProjectExtensions>
<PropertyGroup>
+1 -3
View File
@@ -91,13 +91,11 @@ namespace Disco.Services.Plugins
{
return PartialCompiled<ViewType>(null);
}
private void RenderPartialCompiled<ViewType>(TextWriter Writer, object Model)
private void RenderPartialCompiled<ViewType>(TextWriter Writer, object Model) where ViewType : WebViewPage
{
if (Writer == null)
throw new ArgumentNullException("Writer");
WebViewPage page = Activator.CreateInstance(typeof(ViewType)) as WebViewPage;
if (page == null)
throw new InvalidOperationException("Invalid View Type");
page.ViewContext = ViewPage.ViewContext;
page.ViewData = new ViewDataDictionary(Model);
page.InitHelpers();
+1 -1
View File
@@ -11,7 +11,7 @@ using System.Web.Mvc;
namespace Disco.Services.Web
{
[DiscoAuthorize]
public abstract class AuthorizedController : Controller
public abstract class AuthorizedController : BaseController
{
public AuthorizationToken Authorization
{
+15
View File
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Disco.Services.Web
{
[HandleError]
public class BaseController : Controller
{
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ using System.Web.Mvc;
namespace Disco.Services.Web
{
[OutputCache(Duration = 0, Location = System.Web.UI.OutputCacheLocation.None)]
public abstract class DatabaseController : Controller
public abstract class DatabaseController : BaseController
{
protected DiscoDataContext Database;
@@ -0,0 +1,55 @@
using Disco.Services.Authorization;
using Disco.Services.Users;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace Disco.Services.Web
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class HandleErrorAttribute : FilterAttribute, IExceptionFilter
{
private readonly object _typeId = new object();
private const string ViewArea = null;
private const string ViewMaster = "_Layout";
private const string ViewPage = "Error";
public virtual void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
throw new ArgumentNullException("filterContext");
if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
{
Exception ex = filterContext.Exception;
HttpException httpException = new HttpException(null, ex);
int httpExceptionCode = httpException.GetHttpCode();
switch (httpExceptionCode)
{
case (int)HttpStatusCode.InternalServerError: // 500
case (int)HttpStatusCode.Forbidden: // 403
case (int)HttpStatusCode.NotFound: // 403
filterContext.HandleException();
break;
}
}
}
public override object TypeId
{
get
{
return this._typeId;
}
}
}
}
+77
View File
@@ -0,0 +1,77 @@
using Disco.Services.Authorization;
using Disco.Services.Users;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace Disco.Services.Web
{
public static class HelperExtensions
{
public static void HandleException(this ExceptionContext filterContext)
{
var ex = filterContext.Exception;
var contextResponse = filterContext.HttpContext.Response;
LogException(ex);
HttpException httpException = new HttpException(null, ex);
int httpExceptionCode = httpException.GetHttpCode();
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(ex, controllerName, actionName);
ViewResult result = new ViewResult
{
ViewName = "Error",
MasterName = "_Layout",
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
filterContext.Result = result;
filterContext.ExceptionHandled = true;
contextResponse.Clear();
contextResponse.StatusCode = httpExceptionCode;
contextResponse.TrySkipIisCustomErrors = true;
}
public static void HandleException(this HttpApplication httpApplication)
{
var ex = httpApplication.Server.GetLastError();
LogException(ex);
}
private static void LogException(Exception Exception)
{
// Log Exception:
try
{
if (Exception is AccessDeniedException)
{
var accessDeniedException = (AccessDeniedException)Exception;
var resource = accessDeniedException.Resource;
var httpContext = HttpContext.Current;
if (httpContext != null && httpContext.Request != null)
resource = string.Format("{0} [{1}]", resource, httpContext.Request.RawUrl);
AuthorizationLog.LogAccessDenied(UserService.CurrentUserId ?? "[Anonymous]", resource, accessDeniedException.Message);
}
else
{
Disco.Services.Logging.SystemLog.LogException("Global Application Exception Caught", Exception);
}
}
catch (Exception)
{
// Ignore all logging errors
}
}
}
}
+3
View File
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="5.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="4.0.30506.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="2.0.30506.0" targetFramework="net45" />
<package id="Microsoft.AspNet.SignalR.Core" version="1.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.SignalR.Owin" version="1.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="2.0.30506.0" targetFramework="net45" />
<package id="Microsoft.SqlServer.Compact" version="4.0.8876.1" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net40" />
<package id="Newtonsoft.Json" version="5.0.8" targetFramework="net45" />
+2 -23
View File
@@ -1,6 +1,7 @@
using Disco.Data.Repository;
using Disco.Services.Authorization;
using Disco.Services.Users;
using Disco.Services.Web;
using System;
using System.Configuration;
using System.Diagnostics;
@@ -214,29 +215,7 @@ namespace Disco.Web
#region Global Error Logging
void DiscoApplication_Error(object sender, EventArgs e)
{
try
{
var ex = Server.GetLastError();
if (ex is AccessDeniedException)
{
var accessDeniedException = (AccessDeniedException)ex;
var resource = accessDeniedException.Resource;
var httpContext = HttpContext.Current;
if (httpContext != null && httpContext.Request != null)
resource = string.Format("{0} [{1}]", resource, httpContext.Request.RawUrl);
AuthorizationLog.LogAccessDenied(UserService.CurrentUserId ?? "[Anonymous]", resource, accessDeniedException.Message);
}
else
{
Disco.Services.Logging.SystemLog.LogException("Global Application Exception Caught", ex);
}
}
catch (Exception)
{
// Ignore all logging errors
}
this.HandleException();
}
#endregion
}
+35 -7
View File
@@ -1,10 +1,38 @@
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "Error";
}
ViewBag.Title = "Server Error";
<hgroup class="title">
<h1 class="error">Error.</h1>
<h2 class="error">An error occurred while processing your request.</h2>
</hgroup>
var ex = Model.Exception;
while (ex != null)
{
<div class="form" style="width: 650px">
<h2 style="white-space: pre;">@ex.Message</h2>
<table style="background-color: #fff;">
<tr>
<th style="width: 40px;">Type:</th>
<td>
@ex.GetType().Name
</td>
</tr>
<tr>
<th>Stack:
</th>
<td>
<div class="code" style="width: 560px; white-space: pre; overflow: auto;">@ex.StackTrace</div>
</td>
</tr>
</table>
</div>
ex = ex.InnerException;
}
}
<script>
$(function () {
$('#layout_PageHeading').css({ 'background': '#C80000', 'color': '#fff' });
$('#layout_Page').css({ 'background': 'linear-gradient(to top, #F2B0B0, #C80000 200px)' }).find('h2').css({ 'color': '#fff' });
});
</script>
+77 -10
View File
@@ -2,7 +2,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -43,26 +43,93 @@ namespace Disco.Web.Views.Shared
public override void Execute()
{
#line 3 "..\..\Views\Shared\Error.cshtml"
#line 2 "..\..\Views\Shared\Error.cshtml"
ViewBag.Title = "Error";
ViewBag.Title = "Server Error";
var ex = Model.Exception;
while (ex != null)
{
#line default
#line hidden
WriteLiteral("\r\n\r\n<hgroup");
WriteLiteral(" <div");
WriteLiteral(" class=\"title\"");
WriteLiteral(" class=\"form\"");
WriteLiteral(">\r\n <h1");
WriteLiteral(" style=\"width: 650px\"");
WriteLiteral(" class=\"error\"");
WriteLiteral(">\r\n <h2");
WriteLiteral(">Error.</h1>\r\n <h2");
WriteLiteral(" style=\"white-space: pre;\"");
WriteLiteral(" class=\"error\"");
WriteLiteral(">");
WriteLiteral(">An error occurred while processing your request.</h2>\r\n</hgroup>\r\n");
#line 12 "..\..\Views\Shared\Error.cshtml"
Write(ex.Message);
#line default
#line hidden
WriteLiteral("</h2>\r\n <table");
WriteLiteral(" style=\"background-color: #fff;\"");
WriteLiteral(">\r\n <tr>\r\n <th");
WriteLiteral(" style=\"width: 40px;\"");
WriteLiteral(">Type:</th>\r\n <td>\r\n");
WriteLiteral(" ");
#line 17 "..\..\Views\Shared\Error.cshtml"
Write(ex.GetType().Name);
#line default
#line hidden
WriteLiteral("\r\n </td>\r\n </tr>\r\n <tr>\r\n <th" +
">Stack:\r\n </th>\r\n <td>\r\n <div");
WriteLiteral(" class=\"code\"");
WriteLiteral(" style=\"width: 560px; white-space: pre; overflow: auto;\"");
WriteLiteral(">");
#line 24 "..\..\Views\Shared\Error.cshtml"
Write(ex.StackTrace);
#line default
#line hidden
WriteLiteral("</div>\r\n </td>\r\n </tr>\r\n </table>\r\n </div>\r\n");
#line 29 "..\..\Views\Shared\Error.cshtml"
ex = ex.InnerException;
}
#line default
#line hidden
WriteLiteral(@"
<script>
$(function () {
$('#layout_PageHeading').css({ 'background': '#C80000', 'color': '#fff' });
$('#layout_Page').css({ 'background': 'linear-gradient(to top, #F2B0B0, #C80000 200px)' }).find('h2').css({ 'color': '#fff' });
});
</script>
");
}
}
+1 -1
View File
@@ -24,7 +24,7 @@
</compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Windows" />
<customErrors mode="Off" />
<customErrors mode="On" />
<pages controlRenderingCompatibilityVersion="4.0">
<namespaces>
<add namespace="System.Web.Helpers" />