We have used Umbraco 4.8 as a CMS for application development. When any error occurs in application it need to redirect to tech error page, and we need to log the error in database. So that we are trying to do with application_error event in `global.asax', but unable to add global.asax and application_error in umbraco.
Is there any way to add global.asax or application_error event in Umbraco 4.8?
please help me to resolve this problem.
Thanks,
fazalu.
public class corHandleErrors : System.Web.HttpApplication
{
protected override void Application_Error(object sender, EventArgs e)
{
}
}
Should do the trick
Related
I am running Sitecore 6.6.0-Update 4, MVC. When I attempt to load the Content Editor, all resources load normally except for the /WebResource.axd and /ScriptResource.axd files. This causes errors when attempting to load the Rich Text Editor, and presumably causes errors elsewhere, as well.
I have verified that routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); is present in Global.asax. Is there anywhere else I can look to troubleshoot this issue?
Here is a copy of one of the error messages, retrieved from Fiddler:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Specified method is not supported.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NotSupportedException: Specified method is not supported.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NotSupportedException: Specified method is not supported.]
System.Web.Routing.StopRoutingHandler.GetHttpHandler(RequestContext requestContext) +36
Sitecore.Mvc.Routing.RouteHandlerWrapper.GetHttpHandler(RequestContext requestContext) +33
System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context) +11507752
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web .HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
What version of MVC did you use? Sitecore 6.6 only supports MVC3, you will get errors with MVC4.
Also - are you using the Sitecore supplied Global.asax or the standard MVC one? The Sitecore version should not have any routing info in there. Here is a copy of my global asax from a 6.6 MVC implementation:
<%#Application Language='C#' Inherits="Sitecore.Web.Application" %>
<script runat="server">
public void Application_Start() {
}
public void Application_End() {
}
public void Application_Error(object sender, EventArgs args) {
}
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
{
string frameworkVersion = this.GetFrameworkVersion();
if (!string.IsNullOrEmpty(frameworkVersion) && frameworkVersion.StartsWith("v4.", StringComparison.InvariantCultureIgnoreCase))
{
args.User = Sitecore.Context.User;
}
}
string GetFrameworkVersion()
{
try
{
return System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion();
}
catch(Exception ex)
{
Sitecore.Diagnostics.Log.Error("Cannot get framework version", ex, this);
return string.Empty;
}
}
</script>
How did you setup MVC? If in doubt follow John Wests blog on setting it up.
I'm using Sitecore 6.6 with MVC 4 and everything is working fine. I had same problem as yours, but I commented this line
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // commented this line
in Global.asax and this helps.
I have this
public class ExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
Exception exception = context.Exception;
if (!(exception is HttpException))
{
Trace.TraceError("ExceptionFilter: " + ExceptionUtilities.GetFullExceptionMessage(exception));
Trace.Flush();
}
}
}
and this in global.asax
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new Filters.ExceptionFilter());
filters.Add(new HandleErrorAttribute());
}
but when I trigger an error by creating a dangerous request like this
example.com/dsfgds:dfgd
I get an exception:
A potentially dangerous Request.Path value was detected from the
client (:)
and the filter doesn't fire and the breakpoint inside doesn't get hit.
That's because you're registering an IExceptionFilter with MVC, and as such it will only capture unhandled exceptions that were raised within an MVC Action (and I think maybe other MVC filters? Don't quote me on that). But the error about a potentially dangerous request is an ASP.NET error, the request never made it to MVC, so the MVC error filter never gets called. Likewise, any IIS level errors would also not be handled by this. For non-MVC errors you still need to monitor the Application_OnError event. Or in the case of exception handlers like Elmah, let it monitor the event for you.
I have enabled the global error handling for an application by applying the HandleError attribute within the filterConfig registration.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
I am then using the custom errors (web.config) to hopefully display a friendly error message for each server error.
<customErrors mode="On" ></customErrors>
This seemed to be working fine for most exceptions and I was getting the expected behaviour in that the custom error page View (Error.cshtml in the shared view folder) was being displayed.
However I have recently noticed that this is not the behaviour I see if the error thrown is an UnauthorizedAccessException.
I am a bit stumped with this, as looking in fiddler I see that this UnauthorizedAccessException exception returns a plain 500 internal server error as a standard exception does.
So how come the standard exception abides by my customError setup but the UnauthorizedAccessException does not?
ANd how can I get them to behave the same, as they are both essentially an error which I want to prevent the end user from seeing.
This blog post provided me with the overview of exception handling to enable me to decide how to handle the unauthorizedAccessException, which essentially means handling them within the Application_OnStart.
http://prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc
For my purposes there doesn't seem much point in handling the errors with the HandleErrorAttribute and in the global Application_OnStart so for my purposes I decided it was best to handle everything in the Application_OnSTart,
If you just want to force 'unhandled' exceptions like UnauthorizedAccessException to go through the normal custom-error page then you can override the controller's OnException method similar to the following:
protected override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
if (!filterContext.ExceptionHandled && filterContext.RequestContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
filterContext.Result = View("Error",
new HandleErrorInfo(filterContext.Exception, filterContext.GetCurrentControllerName(), filterContext.GetCurrentActionName()));
}
}
The article that you referenced is an excellent resource for a more thorough explanation of error-handling techniques, though, and should be considered as well.
I have read articles on exception handling in ASP.NET MVC. I want to make sure I am doing right by presenting it briefly. Could anyone please comment.
Catch the exceptions in controller actions, if necessary.
[HttpPost]
public ActionResult Insert()
{
try
{
}
catch
{
//ModelState.Error -> display error msg to the user.
}
}
Override the "OnException" method of controller in basecontroller and "log" the exceptions raised in step 1 and other MVC exceptions
Logged the global exceptions in application_onerror.
I would definitely recommend ELMaH instead of writing this code yourself, and also over Log4Net for your MVC apps. I personally avoid any exception handling, unless I have a specific functional response to it. In this way, I don't "eat" any of the errors that an application-wide tool such as ELMaH will handle gracefully for me.
ELMaH also has nice built-in web reporting, and there are third-party tools specifically for ELMaH that can give you statistics, e.g. the most frequent errors.
You might start with a custom error redirect...
<customErrors defaultRedirect="~/site/error" mode="RemoteOnly">
<error statusCode="404" redirect="~/site/notfound" />
</customErrors>
...to a controller that is aware you are using ELMaH...
public virtual ActionResult Error() {
System.Collections.IList errorList = new System.Collections.ArrayList();
ErrorLog.GetDefault(System.Web.HttpContext.Current).GetErrors(0, 1, errorList);
ErrorLogEntry entry = null;
if (errorList.Count > 0) {
entry = errorList[0] as Elmah.ErrorLogEntry;
}
return View(entry);
}
...backed by a view that helps the visitor get the specific error ID to you:
#model Elmah.ErrorLogEntry
#if (Context.User.Identity.IsAuthenticated) {
<p>Since you are signed in, we've noted your contact information,
and may follow up regarding this to help improve our product.</p>
} else {
<p>Since you aren't signed in, we won't contact you regarding this.</p>
}
<p>Error ID: #Model.Id</p>
I also notice this is an HttpPost in this example. If you are doing AJAX, then you'll want to handle errors for those in a unique way. Pick a standard response you can send to browsers that all of your AJAX code handles gracefully. Perhaps by displaying the ELMaH error ID in a javascript alert (as a simple example).
I also handle a few special types of AJAX errors via Global.asax:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 302 &&
Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
HandleErrorAttribute is a nice feature, but it is well-known that there is extra work to use it in conjunction with ELMaH. How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?
If you want handle exceptions in your Actions you can override "OnException" in your Controller like so:
protected override void OnException(ExceptionContext filterContext)
{
logging or user notification code here
}
You can put it in your BaseController class to prevent duplication
try and catch are for expected exceptions ie your user has entered a file name and it might not exist so you want to catch the FileNotFoundException.
For unexpected exceptions use either the Error event in the MvcApplication object e.g.
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
this.Error += MvcApplication_Error;
// Other code
}
private void MvcApplication_Error(object sender, EventArgs e)
{
Exception exception = this.Server.GetLastError();
// Do logging here.
}
}
or as Dima suggested you have controller level execption handling using
protected override void OnException(ExceptionContext filterContext)
{
// Do logging here.
}
Keep the trys and catches on code where you want to catch something expected and can handle.
"Generic" error handling just obfuscates the underlying problem, which you will have to dig for later.
I have mvc 3 application which when a Standard generic throw new Exception is thrown in code the error page from Views\Shared\error.cshtml is shown. This is done by simply setting <customErrors mode="On"/>. (This is As expected and as Desired)
The application is using WCF services in middle tier which when these services generate FaultException MVC is not showing up the error page it is showing details of the web service call to the user on screen. All I want to do is handle the error in my code and show the user the Error.cshtml. I have tried changing global asax but this dosent work.
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
if (exception.GetType() == typeof(FaultException))
{
throw new Exception("There was a fault exception that i do not want to show details of to user.");
}
}
Try creating an ErrorController as asp.net MVC will try to resolve the link you specified in the web.config as {Controller}/{View} unless you specify it to ignore that page. Also, you may want to apply an attribute to handle exceptions instead.
You can also create a error controller/view and in your catch block redirect to the custom error page of your choosing
try
{
foo.bar()
}
catch(SpecificException)
{
RedirectToAction("500", "Error");
}