A forgotten corner.-exception (ii)

Source: Internet
Author: User
Tags datetime exception handling log reflection serialization static class thread

In the last article, with you briefly introduced the exception, but also so that everyone fully understand the importance of exception management in a project, then how to deal with the exception in our project? Because I am engaged in web development, so I just talk to you about the Web solution, win the solution, but also hope to discuss with you.

In the previous chapter we learned the cause of the anomaly, at the same time also said there is no bug-free program, any site will encounter a variety of problems, whether large or small sites will exist, but large companies and small companies to treat abnormal attitude is completely different, one is active attack, one is waiting, we are good developers , we can't sit and wait, we have to take the initiative. All right, cut the crap.

Now the website generally uses the multi-layer development, the multi-level development time, where should we handle the exception, in throws the exception? Microsoft's idea is that class-Library developers try not to handle exceptions, class library should be written in accordance with the normal logic to write, of course, there are exceptions, notice can see "", OK, according to the specification, we should try to capture and deal with the top, then how do we capture, capture how to deal with, catch what anomalies? Although Microsoft provides a lot of system exceptions, but these exceptions are responsible for throwing the relevant information, and not for the record, or the occurrence of high-level anomalies, timely notify us, such a practice or wait, we still should be active to deal with it. The good news is that Microsoft allows us to create custom exception, preferably by setting a custom exception base class so that your other custom exception will inherit this class for better expansion in the future. Throwing an exception is actually a very performance-intensive operation, but godfather Richer says that the performance of throwing an exception is very small compared to the stability of your program. So we still tend to be stable. Because the performance consumption of handling exceptions is only generated when an exception occurs, we can ignore the performance problems. (Perhaps this is a mouthful, but I tend to be more stable than the system's performance)

How do I create a custom exception?

I have to say that Microsoft is too thoughtful, to create a custom exception is very simple. Open VS, create a project, then add a class, within the namespace range, enter exception, then 2 Tab,vs to help you create a custom exception. Exception, you can see MSDN for the related properties and methods. But automatically created exception are inherited System.Exception, according to Microsoft's original assumption, the custom exception should inherit System.ApplicationException (ironically, Microsoft itself did not comply with this agreement). We set this as our exception base class Mybaseexception.

Code Snippets:

[global::System.Serializable]
public class MyBaseException : ApplicationException
{
public MyBaseException() { }
public MyBaseException(string message) : base(message) { }
public MyBaseException(string message, Exception inner) : base(message, inner) { }
protected MyBaseException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}

This is a standard custom exception, and the other custom exception should be defined according to your project.

Before we go into other definitions, let's think about what we need to do after we capture these exception. We need to know all kinds of information about anomalies, so we need log. Log makes it easy for us to look up the exception and log exception information that occurred. Log has a number of ways, roughly the following:

Text record

Database records

System event Logging (Trace)

Third-party components (log4net)

There are pros and cons to each of these ways, depending on the needs of the project, you can also choose from several ways, such as our default text record, but when we create the log system.ioexception, we have to choose another way to log.

Log mode Ease of Lookup Sex Security Combination of
Text record Convenient So so Low High
Database records So so Convenient So so High
System Event Logging Complex Complex High So so
Third-party components Complex So so So so Low

I have listed several ways of pros and cons, you can have the choice of conditions. If you've already used Third-party component logging in your project, I recommend that you use it. In the solution behind me, I will use the first 2 more common ways to combine.

The purpose of log is to provide our developers with the time, place, character, and cause of the anomaly, so we have to record as much detail as we can to get information based on a exception:

Data Source
Dates and times DateTime.Now
Source of Exception Exception.source
Type of Exception Object.GetType
Exception message Exception.Message
Current method Reflection.MethodInfo.GetCurrentMethod
Machine Name Environment.MachineName or Dns.gethostname
Currentip Dns.gethostbyname ("host"). Addresslist[0]. Address
Call Stack Exception.stacktrace or Environment.stacktrace
OS Information Environment.osversion
Applcation Domain Appdomain.friendlyname
Current Assembly Reflection.Assembly.GetExecutingAssembly
Root Error Cause Exception.getbaseexception
Chained Exception Exception.innerexception
Assembly Version Included in Assemblyname.fullname
Thread ID Appdomain.getcurrentthreadid
Thread User Threading.Thread.CurrentPrincipal

We can build the log information we need according to the table above. For the convenience of management, we should use the same format for log. Here is a message format I wrote for reference:

public static class ExceptionLogFormatHelper
{
public static string ExceptionLogFormatter(Exception ex)
{
StringBuilder sbLog = new StringBuilder("\r\n------------------------------------\r\n");
Exception ochainException = ex;
var currentExceptionIndex = 1;
while (ochainException != null)
{
sbLog.Append("\r\nException " + currentExceptionIndex + " )")
.Append("\r\nException Type:" + ochainException.GetType().FullName)
.Append("\r\nException Source:" + ochainException.Source)
.Append("\r\nException Message:" + ochainException.Message)
.Append("\r\nException Date:" + DateTime.Now)
.Append("\r\nEnvironment Stack:" + System.Environment.StackTrace);
ochainException = ochainException.InnerException;
currentExceptionIndex++;
}
sbLog.Append("\r\n------------------------------------\r\n");
return sbLog.ToString();
}
}

You can also build such a method based on the information you want.

This article is a bit more nonsense, but it is necessary to understand. Also describes the creation of custom exceptions, the comparison of log methods, in the next, I will introduce the notification, exception handling process, and define one's own mybaseexception.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.