Asp.Net MVC Error Handling & logging - asp.net-mvc

I am trying to Catch exceptions and log it.
Presently I have written a Utility method and Passing the Exception to it in the catch block and finally logging the application using MS Enterprise Library 4.0.
I want to know is there any other better way to log errors.
Show exception message in the same view for some type of exceptions for rest navigate to error page.
If someone can help me on this!
Navish

You could try elmah for error logging if that is what you are looking for.

If you were rolling your own Exception logging you could create a base Controller class that overrides the OnException method
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
ExceptionPolicy.HandleException(filterContext.Exception, "MyPolicy");
base.OnException(filterContext);
}
}

Elmah
Elmah could be great option for you. It is easy to use, after installing nuget package is ready for use.
Custom logging with log4net etc.
If you want to log errors by your own, I recommend this example app: https://github.com/mholec/mvcexceptionhandler where is explained global logging with your favorite log tool (log4net, nlog, etc.)
Application Insights
Another and maybe the best way is to use Application Insights. Application Insights you can install quickly using NuGet and you will get great overview of your application errors, website availability and you can get more information about your users. This service is free.

I recommend ELMAH http://code.google.com/p/elmah/
You can get started very quickly with it by using Nuget to set it up.
http://nuget.codeplex.com/
Setup Nuget.
In vstudio ->
View -> Other Windows -> Package
Manager
List-Package -filter elmah
install-package elmah and
you're all set.
You can view the log just like trace.axd by going to http://mysite/elmah.axd
and manually throw errors to elmah like this:
try {
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
hope that helps,
-fs

Related

ASP.NET MVC Global Error Handling with ELMAH - best practices

I really would like to integrate ELMAH into my MVC4 application but I'm having a few issues:
if elmah redirects all errors to a specific error page, do I only need to return success (eg for update, delete, ...) to the user?
if elmah catches all errors do i need to handle errors (e.g. use try catchblocks) in my code at all?
is there a best practise example somewhere how to use ELMAH?
1) Elmah does do any redirects, so you have handle error pages yourself in web.config (hot ot do this you can look here)
2) You should. Elmah is for logging unhandled exceptions. You can log handled exceptions like this:
try
{
.....
}
catch(Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
3) There is a nice article is on Scott Hanselman blog: ELMAH: Error Logging Modules and Handlers for ASP.NET (and MVC too!)

Clarification on using ELAMH in ASP.NET MVC

Am currently using mvc4 with vs2012 and i installed mvc.elmah nugget and am done.
What i did ?
Initially i didnt write any code and my exception were logged in ELMAH.
Later i decided to use MVC HandleError to handle Application Exceptions and added filter
filters.Add(new HandleErrorAttribute());
Now i debugged in filters and see i have 2 filters one for ELMAH HandleErrorAttribute and MVC HandleErrorAttribute !
I saw this excellent link https://stackoverflow.com/a/5936867/1481690 which talks about using ErrorSignal to handle Application Exceptions
But am not using ErrorSignal but still my Exceptions are captured by ELMAH ?
If i use
if (context.ExceptionHandled)
ErrorSignal.FromCurrentContext().Raise(context.Exception);
My Exceptions are logged twice.
My Question as follows
Do i need to use 2 filters(ELMAH and MVC) ?
If ELMAH is already having HandleErrorAttribute and log exception. Do i need to add MVC HandleErrorAttribute ?
What am doing currently is
Added filters
filters.Add(new HandleErrorAttribute());
and overriding (To handle Ajax Error in future)
public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
}
Is this enough or what is the good practise ? Am not raising ErrorSignal as it is logging twice.
Am not using any try.catch as am using below line and hope my exception is handled.
base.OnException(context);
}
Just want to make sure that am on right way !
Thanks for the time
UPDATE: I pointed to the wrong package updating question.
You don't need both. ElmahHandleErrorAttribute inherits from HandleErrorAttribute, so using both is redundant.
How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?
You also do not need to raise any signals for Elmah, the ElmahHandleErrorAttribute handles this.
If you're using Elmah.Contrib.MVC from Nuget all you need is ElmahHandleErrorAttribute.
filters.Add(new Elmah.Contrib.MVC.ElmahHandleErrorAttribute());
There's also a package on there that I mistook for this one at Elmah.MVC done by the same author as Elmah, I'm looking into this one to find out what the differences are and how to use it.
UPDATE 2: Ok, so apparently the Elmah.MVC package has all of this built in, and they register pretty much everything for you using WebActivator. So literally all you need to do on a brand new MVC project to start tracking errors with Elmah is to install the package, and compile. Done. However you should check your web.config after installing it, and under AppSettings, set the role required to view the page and enable the authentication.
I believe the way you have it is correct. This is in my Global.asax.cs
private static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ElmahHandleErrorAttribute());
filters.Add(new HandleErrorAttribute());
}
One thing to check is that your controllers do not have either [ElmahHandleError] or [HandleError] attributes.

Errors are logged twice when using Elmah with WebApi

I'm trying to log exceptions from my asp.net web api project using elmah. I am having an issue where each error is logged twice.
I am using Elmah.Contrib.Web-Api and my Application class is as follows:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
RouteTable.Routes.MapHubs();
RouteConfig.RegisterRoutes(RouteTable.Routes);
#if DEBUG
EntityFrameworkProfiler.Initialize();
#endif
GlobalConfig.CustomizeConfig(GlobalConfiguration.Configuration);
}
}
If I commment out the following line then I get no messages at all:
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
And I can confirm that I am only throwing one error and the call which generates the error is only been called once and I've not manually decorated my controllers or methods with the Elmah Attribute.
To try and resolve this I removed The Contrib Package and added followed the instructions found here http://www.tugberkugurlu.com/archive/asp-net-web-api-and-elmah-integration
This did not solve the issue and it still logs twice. It did allow me to put a break point into the Attribute class and confirm that for each error it is being called twice.
How can I solve this?
What ELMAH-related entries are in your web.config?
I had a similar issue in an MVC application - handled exceptions were being logged twice. In the application I use a custom exception filter to log handled exceptions to ELMAH using error signalling, while the HTTP module takes care of unhandled exceptions.
It turned out that I needed to set:
<add key="elmah.mvc.disableHandleErrorFilter" value="true" />
in web.config in order to disable the built-in exception filter within the ELMAH.MVC NuGet package.
The source code for the built-in filter shows that it logs handled exceptions:
https://github.com/alexanderbeletsky/elmah-mvc/blob/master/src/Elmah.Mvc/HandleErrorAttribute.cs
I'd check your FilterConfig.cs class, it's possible that the default HandleErrorAttribute is being added there and is re-throwing your exception?
For what it's worth, I was having the same problem of ELMAH logging each exception twice in my Web API application (using Elmah.Contrib.WebApi).
Comparing my ELMAH emails against my source history, I was able to identify that the problem started happening after the Ninject.Web.WebApi 3.0.2-unstable-9016 package was installed via nuget.
Sure enough, uninstalling the package and commenting out the single dependency binding that was using it solved the double exception logging problem. Reinstalling the package and leaving the dependency binding commented out caused the problem to start again, so it wasn't the binding itself.
Installing the previous version (Ninject.Web.WebApi 3.0.2-unstable-8) did not cause the problem to happen, but my dependency binding no longer worked.
I'm choosing to live with the problem for the time being.
Have you seen this post ? The author uses an ExceptionFilter to handle logging exceptions
For other folks with the logging twice issue (I don't think this helps the OP?) - this happened to me and the reason was because I had applied the filter globally
GlobalConfiguration.Configuration.Filters.Add(new ElmahErrorAttribute()); //log web api errors
but also applied the attribute to the class (doh!)
[ElmahError]
public class TestController : ApiController
So of course it logged twice.
I had this problem occur only on HTTP 401 responses. The issue turned out to be that Windows Authentication was enabled which was causing the browser to make a second negotiation request.
In my case, I was just able to disable Windows Authentication in the web.config:
<security>
<authentication>
<windowsAuthentication enabled="false" />
</authentication>
</security>
Note: If you don't have the config section unlocked, you can just disable Windows Authentication in IIS.

Globally manage unexpected exception in asp.net MVC

I'm coming at the end of the development of my application.
Everything is working fine, but if once somebody got an unexpected exception, I would like to be able to:
Redirect him to a user-friendly page explaining that we got a problem.(Specifying a controller/action)
Log every information of the stack trace, current controller/action, parameter, session data, ...
What is the best way to do it with asp.net MVC?
EDIT
In complement of the great answer:
I integrated elmah like described here: http://joel.net/logging-errors-with-elmah-in-asp.net-mvc-3--part-1--setup
And then I specified some custom error page. So now I've all I need!
I would recommend you use "Elmah" http://code.google.com/p/elmah/
This package is a godsend - does exactly what is shown on the box, with close to ZERO changes to your source code.
It is also available via NuGet at http://nuget.org/packages/elmah
Use action filters.
http://blogs.msdn.com/b/gduthie/archive/2011/03/17/get-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx
You can catch errors in the global.asax. There is a method protected void Application_Error(object sender, EventArgs e) where you can do what ever you want.
Take a look at PostSharp, neat and easy to use. Starter version available to use after free registration. NuGet package also available http://nuget.org/packages/PostSharp

Exceptions in N2cms page

i'm using n2cms + asp.net mvc,
when the site is uploaded to a webserver, and an exception is thrown in the aspx page, the page appear blank, and there is nothing in the page, even if i turned off the CustomErrors in web.config
but when the site is running on my computer visual studio simply show me the exception,
is there a way to catch the exception in this situation?
This may be due to your hosting configuration. You could take a look at ELMAH for an easy way of logging exceptions.
You can handle all global errors in your Global.asax's method called Application_Error - http://msdn.microsoft.com/en-us/library/24395wz3.aspx . It will work for simple cases. But I strongly recommend to use ELMAH
N2CMS makes calls to SwallowExceptions(). This is why you are receiving a blank page instead of an exception. You could look for that method call and comment it.

Resources