C # capture global exceptions using winform

Source: Internet
Author: User

C # capture global exceptions using winform

Many small companies lack Exception Handling modules. This is often the case. When you operate on the UI, the stack call exception information dialog box pops up. The boss sees it as a fire! How can your code be garbled every day. Haha! This is caused by no exception capture and processing. Now many people write code and are unaware of exception handling. As long as the function is implemented, this is also true for many of my team members.

The project has just taken over, so we plan to implement a global exception capture and unified processing mode, and adopt the dialog box reminder and log file saving mode for specific details. The following changes are made based on the global exception capture function C # winform found on the Internet.

Static class Program
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
Try
{
// Set the Exception Handling Method of the application: threadexception handling
Application. setunhandledexceptionmode (unhandledexceptionmode. catchexception );
// Handle UI thread exceptions
Application. threadexception + = new system. Threading. threadexceptioneventhandler (application_threadexception );
// Handle non-UI thread exceptions
Appdomain. currentdomain. unhandledexception + = new unhandledexceptioneventhandler (currentdomain_unhandledexception );
 
# Main entry point of the region Application
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault (false );
Application. Run (New form1 ());
# Endregion
}
Catch (exception ex)
{
String STR = getexceptionmsg (ex, String. Empty );
MessageBox. Show (STR, "system error", messageboxbuttons. OK, messageboxicon. Error );
}
}
 
 
Static void application_threadexception (Object sender, system. Threading. threadexceptioneventargs E)
{
String STR = getexceptionmsg (E. exception, E. tostring ());
MessageBox. Show (STR, "system error", messageboxbuttons. OK, messageboxicon. Error );
// Logmanager. writelog (STR );
}
 
Static void currentdomain_unhandledexception (Object sender, unhandledexceptioneventargs E)
{
String STR = getexceptionmsg (E. exceptionobject as exception, E. tostring ());
MessageBox. Show (STR, "system error", messageboxbuttons. OK, messageboxicon. Error );
// Logmanager. writelog (STR );
}
 
/// <Summary>
/// Generate custom exception messages
/// </Summary>
/// <Param name = "ex"> exception object </param>
/// <Param name = "backstr"> standby exception message: valid when ex is null </param>
/// <Returns> abnormal string text </returns>
Static string getexceptionmsg (exception ex, string backstr)
{
Stringbuilder sb = new stringbuilder ();
SB. appendline ******* *********************");
SB. appendline ("[occurrence time]:" + datetime. Now. tostring ());
If (ex! = NULL)
{
SB. appendline ("[Exception type]:" + ex. GetType (). Name );
SB. appendline ("[exception information]:" + ex. Message );
SB. appendline ("[stack call]:" + ex. stacktrace );
}
Else
{
SB. appendline ("[unprocessed exception]:" + backstr );
}
SB. appendline ("************************************* **************************");
Return sb. tostring ();
}
}

-----------------
Use log4.net for logging

The following configuration is placed in APP. config and placed under <configuration>.

------ Config begin -------
<Configsections>
<Section name = "log4net" type = "log4net. config. log4netconfigurationsectionhandler, log4net"/>
</Configsections>
<Log4net DEBUG = "true">
<Logger name = "admin">
<! -- Control log level: All | debug | info | warn | error | fatal | off -->
<Level value = "debug"/>
<Appender-ref = "rollingfile"/>
</Logger>
<Appender name = "rollingfile" type = "log4net. appender. rollingfileappender, log4net">
<Param name = "file" type = "" value = "logs \"/>
<Param name = "appendtofile" value = "true"/>
<Param name = "maxsizerollbackups" value = "10"/>
<Param name = "rollingstyle" value = "date"/>
<Param name = "datepattern" value = "yyyymmdd & quot;. log & quot;"/>
<Param name = "staticlogfilename" value = "false"/>
<Layout type = "log4net. layout. patternlayout, log4net">
<Param name = "conversionpattern" value = "% d % 5 P: % m % N"/>
</Layout>
</Appender>
</Log4net>

--- Config end ---

Put the log. CS file in a public place.

Directly use the location to be recorded in the program
Sharelibrary. log. debug (STR );
Or
Sharelibrary. log. debug (Ex );

---------- CS begin -----------

Using system;
Using system. Collections. Generic;
Using system. text;
Using log4net;

Namespace sharelibrary
{
Public class log
{

Private Static log4net. ilog log = log4net. logmanager. getlogger ("admin ");
Public static void debug (string message)
{
If (log. isdebugenabled)
{
Log. debug (Message );
}
}
/// <Summary>
/// Record abnormal information, log4net
/// </Summary>
/// <Param name = "ex1"> </param>
Public static void debug (system. Exception ex1)
{
If (! Log. isdebugenabled)
{
// If not available, reconfigure
Log4net. config. xmlconfigurator. Configure ();
}
Log. debug (ex1.message. tostring () + "\ r \ n" + ex1.source. tostring () + "\ r \ n" + ex1.targetsite. tostring () + "\ r \ n" + ex1.stacktrace. tostring ());
// If (log. isdebugenabled)
//{


// Log. debug (ex1.message. tostring () + "\ r \ n" + ex1.source. tostring () + "\ r \ n" + ex1.targetsite. tostring () + "\ r \ n" + ex1.stacktrace. tostring ());
//}

}
Public static void error (string message)
{
If (log. iserrorenabled)
{
Log. Error (Message );
}
}
Public static void fatal (string message)
{

If (log. isfatalenabled)
{
Log. Fatal (Message );
}
}
Public static void Info (string message)
{
If (log. isinfoenabled)
{
Log. Info (Message );
}
}

Public static void warn (string message)
{
If (log. iswarnenabled)
{
Log. Warn (Message );
}
}
}
}

----------- End of CS ---------------

 

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.