handling errors outside of exceptions - c#

I setup an exception handling class to log errors to the database which works really well but I was wondering if I can also somehow setup the application so any error outside of a try catch will call the same procedure somehow?
It works well most of the time and shows a screen with an error code to the user but I want to be able to use this friendly error screen each time but on the odd occasion an error outside of the try catch is thrown and it shows the normal asp.net error.
The catch I use:
catch (SqlException ex)
{
ExceptionHandling.SQLException(ex, constPageID, constIsSiteSpecific);
}

It is possible to use the Global.asax's Application_Error method.
protected void Application_Error()
{
Exception exception = Server.GetLastError();//Get the Last Error
LogException(exception);//Custom Code
}
However be aware that if you do any error a user suffers will direct them onto your error page. It's often better to handle smaller errors on the page itself and present a simple message.
There are countless discussions on proper error handling - personally I like to catch everything the UI method which called it (OnPreRender, OnLoad OnEvent etc).

If you are developing an ASP.NET application, you can log unhandled exceptions in Global.asax in "Application_Error" method.
protected void Application_Error()
{
Exception exception = Server.GetLastError();
// Clear the error
Server.ClearError();
// Log exception
}

Related

Exception Handling in ASP.NET (C#) from a separate class file

I am writing an ASP.NET application in C# and I am working on handling possible exceptions that may be thrown from another file. I have a C# class file that I wrote containing methods that execute SQL commands, and I want to protect against possible exceptions being thrown once my application goes into production.
This is the SQL method I wrote that I am intentionally throwing an error in (From SqlData.cs):
public SqlConnection openConnection()
{
//Create an SQL connection
SqlConnection myConnection = new SqlConnection("My intentionally incorrect connection string");
//Open the connection
try
{
myConnection.Open();
}
catch (SqlException myAppEx)
{
throw new ApplicationException("There was an error opening the SQL database connection", myAppEx);
}
return myConnection;
}
I call this method from my Default.aspx.cs file with the following lines of code:
try
{
//The ReadDT method calls openConnection() in itself
dt = sqlData.ReadDT(query);
}
catch (ApplicationException exc)
{
throw exc;
}
I am trying to implement Page level exception handling, where if an exception is raised on the current page the Page_Error method is supposed to be called, as cited here. This is why I catch the exception that was thrown from my SqlData.cs class file, and re-throw the exception, so that this exception is seen by the server. Hence, Server.GetLastError() will not return null.
As implemented here, I have a separate error page that displays all of the information on the exception. My Page_Error method is as follows:
private void Page_Error(object sender, EventArgs e)
{
Server.Transfer("ErrorPage.aspx?handler=Page_Error%20-%20Default.aspx", true);
}
From here the user is redirected to my ErrorPage.aspx and the SqlException that was originally thrown is displayed perfectly.
The problem - When I catch the exception from the SqlData.cs, and re-throw the exception, an UnhandledException is raised. if I do not put a try catch block around the ReadDT method call, the same UnhandledException is raised from my SqlData.cs file.
Code trace:
throw new ApplicationException("There was an error opening the SQL database connection", myAppEx); (This works correctly)
The exception is then caught and re-thrown (UnhandledException occurs)
The Page_Error method is called as it should be and everything executes properly!
I hope I have been clear in answering myself, I have done a lot of research on exceptions and my particular problem and I have not had any success in finding an answer.
Thanks,
Eric
In ASP.NET, unhandled exceptions thrown by your application will be wrapped in an HttpUnhandledException before calling the Page or Global error handler. You need to look at its InnerException property to get at the original exception.
In general, you shouldn't bother wrapping and rethrowing exceptions like you're doing unless you're adding value (for example, additional data regarding the context of the exception). Just let them propagage to wherever they're eventually handled (Page_Error in your case, though you might consider using Application_Error in global.asax.cs, to avoid repeating this error handling code on every page).
So I came up with a combination of error handling through Code Level exception handling, and redirecting the user to an error page, then logging the error with ELMAH, to solve my problem.
I now handle all exception's directly in my SqlData class file, for the least yet most efficient code. I have a global variable HttpResponse response in my SqlData class file, that I populate each time I create a new instance of the class from within my ASP.NET application. So from my Main.aspx.cs file I have something like:
private SQLData data;
protected void Page_Load(object sender, EventArgs e)
{
data = new SQLData(Response);
...
}
If I do this I am able to call a response.Redirect() from my class file to send the user to my error page, I pass the exception error message and type of exception in a query string, to which I then print out to the user in my error page. This allows me to display only non-sensitive information to the user. Therefore the exception has been handled and ELMAH has logged all of the specifics!
//Create an SQL connection
SqlConnection myConnection = new SqlConnection("MyConnString");
//Open the connection
try
{
myConnection.Open();
}
catch (Exception ex)
{
//Manually log the exception in ELMAH
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
//Redirect the user to the error page
response.Redirect("ErrorPage.aspx?ErrorMessage=" + ex.Message + "&ErrorType=SQLException", true);
}
return myConnection;
I then have a link display at the bottom of my error page directing to the elamh.axd page only if you are an administrator. From this page you may view the stack trace and other sensitive information.
You can find information on ELMAH at the bottom of this page as well as setting up ELMAH in an ASP.NET application. It is very easy to do, and a very powerful tool.
Cheers,
Eric

Is there a way to execute a block of code during any uncaught exception?

I realize this is a shot in the dark and not the best practice or way of going about it, but I want to do specific logging information as the exception is thrown. It is important that the state of the web form does not change.
You can use
try
{
}
catch(Exception ex)
{
//your treatment does not contain throw ex.
//mute exception in order to not change state
}
You can use this in your webform or in your gloabl.asax in Application_Error (in order to centralize exception treatment)
try
{
ExceptionProneCode()
}
catch(Exception ex)
{
WriteToSomeLogFile(ex.Message);
//if you want the exception to bubble up from this point,
//than you would type "throw;"
}
If we are talking in the context of ASP.NET, the Application_Error event would be a good place to put a global exception logging block.

Getting exception that caused program to crash without being in debug mode

I have an application in C# that I want to run by just running the .exe from my desktop. However, I'm pretty sure there will be some type of error that will make the program crash. Is there a way to write the problem that caused the program to crash to a text file, so that I can see what caused the issue when users are using the program? I know I can use debug mode to do this but I want to run the application as a stand alone not inside of VS.
Thanks,
I am aware of the try catch blocks and I am already using those where problems might occur. But I am speaking in general. For example if I wasn't sure where the problem would occur. There is no way to print this specific error to a file.
You can try the global try/catch method except that if there is an exception on a background thread it won't be caught. You can use AppDomain.UnhandledException if you want to be notified of any unhandled exception in the appdomain (msdn). You would signup in main before the rest of your program executes like so:
static void Main(string[] args)
{
AppDomain.UnhandledException += WriteUnhandledExceptionToFile;
// rest of program
}
static void WriteUnhandledExceptionToFile(object sender, UnhandledExceptionEventArgs args)
{
// write to where ever you can get it.
string path = Path.Combine(Environment.CurrentDirectory, "UnhandledException.txt");
File.WriteAllText(path, args.ExceptionObject.ToString()); // will print message and full stack trace.
}
Edit
Note that by default Windows Forms and WPF catch any exceptions that are thrown on the UI thread. You will have to subscribe to the Application.ThreadException event (forms) or Application.DispatcherUnhandledException event (wpf) to be notified of exceptions on those threads. The code would be very similar to the code above for the AppDomain event.
Have a global exception handler that writes the exception details to a file.
If you wrap the code in your Main method in a try{}catch{} block, you can write out the exception details in the catch block.
try
{
// Calls to application code
}
catch(Exception ex)
{
// log `ex.ToString()`
throw; // rethrow to ensure termination optionally: `Application.Exit`
}
Even if you aren't logging the problem, you can usually get the error in question from the event viewer within windows.
The first thing you want to look at is the try/catch construct in C#. This is probably your first building block to handling errors.
As for how you handle the errors, that's entirely up to you. Currently your only stated goal is to log them to a file. You can get a lot of details out of the Exception object that you catch and you can write those details to a file. Additionally, you can use logging libraries to help with that sort of thing.
Proper error handling is something of a big subject, really. One thing to keep in mind is logically where you want to catch the exception. Ideally, you want to catch it where you can handle it. That is, where your code can sufficiently recover from the error. If it's a fatal error and the application should stop entirely, then you can throw the exception further up the stack and let it go unhandled (though still logged where you caught it).
If, however, you're in a logical condition where you can just log the error and move on, then the catch block allows you to do just that. Log the details, update the state of any objects/data which need to be updated, and continue with the flow of the application.
you can surround your one of the starting method with try catch block
try
{
///Your code
}
catch(Exception exception)
{
System.IO.File.WriteAllLines("ErrLog.txt", exception.Message);
}
As a permanent solution you can create extension method ToLog and use it whenever you want.
public static void ToLog(this Exception Exception)
{
using (var file = File.AppendText("ErrorLog.txt"))
{
file.WriteLine(DateTime.Now + " : " + exception.Message);
}
}
You can use it in catch block like this
catch(Exception exception)
{
exception.ToLog();
}
See initial information here http://www.csharp-examples.net/catching-unhandled-exceptions/
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception");
}
The UnhandledException event handles uncaught exceptions thrown from the main UI thread. The ThreadException event handles uncaught exceptions thrown from non-UI threads.
I would replace the MessageBox with some actual logging (log4net or others). This would give you the ability to log out the errors to another server for distributed applications, file system for local users, event logs, options are fairly unlimited if you're willing to put in the time.

Exception handling with Elmah

I log exceptions with Elmah and was wondering if the technique I am using is good design?
Right now I catch and re throw exceptions that occur in various classes and methods, and log them to Elmah in the main try-catch block of the program.
// Main Program
try
{
// Some code that fires off other classes, etc...
MyTestClass myTestClass = new MyTestClass();
myTestClass.Execute();
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
// MyTestClass
public class MyTestClass
{
public object ApiResult { get; set; }
public string Execute()
{
try
{
// execute some code
// ....
// set xml message
ApiResult = "User information xml response";
}
catch (Exception ex)
{
// set xml message
ApiResult = "something went wrong xml error response...";
throw;
}
}
}
Would it be better to log the exceptions where they occur? Another question, should I log errors that I can handle without catching exceptions? For example if something is null, should I do a test for that (if null...) and log a message in Elmah?
Rather than manually logging an error using Elmah's ErrorSignal class you should instead strive to let ELMAH log errors for you automatically, which occurs when the application's Error event is raised.
In your example there's a serious problem with Main Program. Namely, it is swallowing exceptions, at least for the end user. Yes, the exception is getting logged in ELMAH but you are hiding the error from the user. The end user will think her form submission (or whatever) went through without error, when in actuality there was a grave problem.
In short, try...catch blocks should only be used sparingly, such as in cases where you can recover from an error or when the error is a "minor" one and should not stop the workflow. But the majority of errors are real show stoppers and don't have graceful workaround. For this majority you'd want to let the error percolate up to the ASP.NET runtime where ELMAH will automatically log it and where the user will see an error page, alerted them to the fact that an error has occurred.
Check out this article of mine: Exception Handling Advice for ASP.NET Web Applications.
I think the following situation will give you an idea for when to use ErrorSignal.FromCurrentContext().Raise(ex);
var bo = new CustomerBO();
bo.Update(customer);
try
{
Email.SendProfileChangedNotification();
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
Response.Redirect(Constants.ProfilePage);
Email.SendProfileChangedNotification method is not so important in this code, I mean, I can leave with it if it has any errors and I don't want to show them to the user. The important part is that his/her profile is updated and the user is aware of it by seeing the profile page.
So I believe there places in code which may fail constantly, I would like to get notified about them, but I don't want to break down the entire action.

Easy way to catch all unhandled exceptions in C#.NET

I have a website built in C#.NET that tends to produce a fairly steady stream of SQL timeouts from various user controls and I want to easily pop some code in to catch all unhandled exceptions and send them to something that can log them and display a friendly message to the user.
How do I, through minimal effort, catch all unhandled exceptions?
this question seems to say it's impossible, but that doesn't make sense to me (and it's about .NET 1.1 in windows apps):
All unhandled exceptions finally passed through Application_Error in global.asax. So, to give general exception message or do logging operations, see Application_Error.
If you need to catch exeptions in all threads the best aproach is to implement UnhandledExceptionModule and add it to you application look here
for an example
Use the Application_Error method in your Global.asax file. Inside your Application_Error method implementation call Server.GetLastError(), log the details of the exception returned by Server.GetLastError() however you wish.
e.g.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
log4net.ILog log = log4net.LogManager.GetLogger(typeof(object));
using (log4net.NDC.Push(this.User.Identity.Name))
{
log.Fatal("Unhandled Exception", Server.GetLastError());
}
}
Don't pay too much attention to the log4net stuff, Server.GetLastError() is the most useful bit, log the details however you prefer.
The ELMAH project sounds worth a try, its list of features include:
ELMAH (Error Logging Modules and
Handlers) is an application-wide error
logging facility that is completely
pluggable. It can be dynamically added
to a running ASP.NET web application,
or even all ASP.NET web applications
on a machine, without any need for
re-compilation or re-deployment.
Logging of nearly all unhandled exceptions.
A web page to remotely view the entire log of recoded exceptions.
A web page to remotely view the full details of any one logged
exception.
In many cases, you can review the original yellow screen of death that
ASP.NET generated for a given
exception, even with customErrors mode
turned off.
An e-mail notification of each error at the time it occurs.
An RSS feed of the last 15 errors from the log.
A number of backing storage implementations for the log
More on using ELMAH from dotnetslackers
You can subscribe to the AppDomain.CurrentDomain.UnhandledException event.
It's probably important to note that you are not supposed to catch unhandled exceptions. If you are having SQL timeout issues, you should specifically catch those.
Do you mean handling it in all threads, including ones created by third-party code? Within "known" threads just catch Exception at the top of the stack.
I'd recommend looking at log4net and seeing if that's suitable for the logging part of the question.
If using .net 2.0 framework, I use the built in Health Monitoring services. There's a nice article describing this method here: https://web.archive.org/web/20210305134220/https://aspnet.4guysfromrolla.com/articles/031407-1.aspx
If you're stuck with the 1.0 framework, I would use ELMAH:
http://msdn.microsoft.com/en-us/library/aa479332.aspx
hope this helps
There are 2 parts to this problem handling & identifying.
Identifying
This is what you do when the exception is finally caught, not necessarily where it is thrown. So the exception at that stage must have enough context information for you to idenitfy what the problem was
Handling
For handling, you can
a) add a HttpModeule. See
http://www.eggheadcafe.com/articles/20060305.asp
I would suggest this approach only when there is absolutely no context informaatn available and there might be issuus wiih IIS/aspnet, In short for catastrophic situations
b) Create a abstract class called AbstractBasePage which derives from Page class and have all your codebehind classes derive from AbstractBasePage
The AbstractBasePage can implement that Page.Error delegate so that all exceptions which percolate up through the n-tier architecture can be caught here(and possibly logged)
I would suggest this cause for the kind of exceptions you are talking about (SQlException) there is enough context information for you to identify that it was a timeout and take possible action. This action might include redirecting user to a custom error page with appropriate message for each different kind of exception (Sql, webservice, async call timeouts etc).
Thanks
RVZ
One short answer is to use (Anonymous) delegate methods with common handling code when the delegate is invoked.
Background: If you have targeted the weak points, or have some boilerplate error handling code you need to universally apply to a particular class of problem, and you don't want to write the same try..catch for every invocation location, (such as updating a specific control on every page, etc).
Case study: A pain point is web forms and saving data to the database. We have a control that displays the saved status to the user, and we wanted to have common error handling code as well as common display without copy-pasting-reuse in every page. Also, each page did it's own thing in it's own way, so the only really common part of the code was the error handling and display.
Now, before being slammed, this is no replacement for a data-access layer and data access code. That's all still assumed to exist, good n-tier separation, etc. This code is UI-layer specific to allow us to write clean UI code and not repeat ourselves. We're big believers in not quashing exceptions, but certain exceptions shouldn't necessitate the user getting a generic error page and losing their work. There will be sql timeouts, servers go down, deadlocks, etc.
A Solution: The way we did it was to pass an anonymous delegate to a method on a custom control and essentially inject the try block using anonymous delegates.
// normal form code.
private void Save()
{
// you can do stuff before and after. normal scoping rules apply
saveControl.InvokeSave(
delegate
{
// everywhere the save control is used, this code is different
// but the class of errors and the stage we are catching them at
// is the same
DataContext.SomeStoredProcedure();
DataContext.SomeOtherStoredProcedure();
DataContext.SubmitChanges();
});
}
The SaveControl itself has the method like:
public delegate void SaveControlDelegate();
public void InvokeSave(SaveControlDelegate saveControlDelegate)
{
// I've changed the code from our code.
// You'll have to make up your own logic.
// this just gives an idea of common handling.
retryButton.Visible = false;
try
{
saveControlDelegate.Invoke();
}
catch (SqlTimeoutException ex)
{
// perform other logic here.
statusLabel.Text = "The server took too long to respond.";
retryButton.Visible = true;
LogSqlTimeoutOnSave(ex);
}
// catch other exceptions as necessary. i.e.
// detect deadlocks
catch (Exception ex)
{
statusLabel.Text = "An unknown Error occurred";
LogGenericExceptionOnSave(ex);
}
SetSavedStatus();
}
There are other ways to achieve this (e.g. common base class, intefaces), but in our case this had the best fit.
This isn't a replacement to a great tool such as Elmah for logging all unhandled exceptions. This is a targeted approach to handling certain exceptions in a standard manner.
Timeout errors typically occur if you are not forcefully closing your sqlconnections.
so if you had a
try {
conn.Open();
cmd.ExecuteReader();
conn.Close();
} catch (SqlException ex) {
//do whatever
}
If anything goes wrong with that ExecuteReader your connection will not be closed. Always add a finally block.
try {
conn.Open();
cmd.ExecuteReader();
conn.Close();
} catch (SqlException ex) {
//do whatever
} finally {
if(conn.State != ConnectionState.Closed)
conn.Close();
}
This is old question, but the best method (for me) is not listed here. So here we are:
ExceptionFilterAttribute is nice and easy solution for me. Source: http://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling.
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var exception = context.Exception;
if(exception is SqlTimeoutException)
{
//do some handling for this type of exception
}
}
}
And attach it to f.e. HomeController:
[ExceptionHandling]
public class HomeController: Controller
{
}

Categories

Resources