"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
Exception handling
1. 1. Exceptions area constructin the .NET Framework thatare (ideally) used to
indicate an unexpected state in executing code.
For example, when working with a databasethe underlying ADO.NETcode
that communicates with the database raises an exception if the database is
offline or if the databasereports an error when executing a query. Similarly,
if you attempt to castuser input fromone type to another - say froma
string to an integer - but the user's inputis not valid, an exception will be
thrown. You can also raise exceptions fromyour own code by using
the Throw keyword.
2. When an exception is thrown it is passed up the call stack. That is,
if MethodA calls MethodB, and then MethodB raises an
exception, MethodA is given the opportunity to execute code in response
to the exception. Specifically, MethodA can do one of two things: it
can catch the exception (using a Try..Catch block) and execute code in
responseto the exception being throw; or it can ignorethe exception and
let it percolate up the call stack. If the exception is percolated up the call
stack - either by MethodA not catching the exception or by MethodA re-
throwing the exception - then the exception information will be passed up
to the method that called MethodA. If no method in the call stack handles
the exception then it will eventually reach the ASP.NET runtime, which will
display the configured error page as shown in the fig below.
3. This kind of error is the un handled error ,means we can not handle the
exception .
2. 4. How to overcome this type of error :
Whenever an unhandled exception occurs, theASP.NETruntime displays its
configured error page. (An unhandled exception is an exception that is not caught
and handled by some method in the call stack when the exception is raised. If no
method in the call stack catches the exception then it percolates all the way up to
the ASP.NETruntime, which then displays the error page as shown above.)
The error page displayed by the ASP.NET runtime depends on two factors:
Whether the website is being visited locally or remotely, and
The <customErrors> configuration in Web.config.
3. 5. While the Yellow Screen of Death error page is acceptable in the
development environment, displaying such an error page in production to
real users smacks of an unprofessionalwebsite. Instead, your ASP.NET
application should usea custom error page. A customerror page is a user-
friendly error page that you create in your project. Unlike the Yellow Screen
of Death error page, a customerror page can match the look and feel of
your existing website and explain to the user that there was a problem and
providesuggestions or steps for the user to take as shown below.
6.For this purposeupdate the web.config file as follow
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="pages/Error.aspx" />
</system.web>
</configuration>
4. =========================================================================================
<customErrors defaultRedirect="url"
mode="On|Off|RemoteOnly">
<error statusCode="statuscode"
redirect="url"/>
</customErrors>
Required Attribute
Attribute Option Description
Mode Specifieswhethercustomerrorsare enabled,disabled,or
shownonlytoremote clients.
On Specifiesthatcustomerrorsare enabled.If
no defaultRedirectisspecified,userssee agenericerror.
Off Specifiesthatcustomerrorsare disabled.Thisallowsdisplayof
detailederrors.
RemoteOnly Specifiesthatcustomerrorsare shownonly toremote clients
and ASP.NETerrorsare showntothe local host.Thisisthe
default.
Optional Attribute
Attribute Description
defaultRedirect Specifiesthe defaultURLto directa browsertoif an error occurs.
WhendefaultRedirectisnotspecified,agenericerrorisdisplayedinstead.The URL
may be absolute (forinstance,http://www.contoso.com/ErrorPage.htm)oritmay
be relative.A relative URLsuchas /ErrorPage.htmisrelative tothe Web.configfile
that specifiedthedefaultRedirectURL,not tothe Webpage in whichthe error
occurred.A URL startingwitha tilde (~),suchas~/ErrorPage.htm,meansthatthe
specifiedURLis relative tothe rootpath of the application.
5. Subtag
Subtag Description
<error> The error subtag can appearmultiple times.Eachappearance definesone custom
error condition.
If someunhandled exceptions come then the page will be reditected to the custo
error page we shall usein the application instead of runtime generated error
page.
7.HandledExceptions :How to track while in production and record the error
messagein notepad with details like time and error message.
i. The handled exceptions are the exceptions which wecome across
many time in the solution.We can see thoseerrors when we are in
running and by applying the debugger. But when the application is
in production we can’t see those errors by applying debuggers .
ii. So we need to create the notepad and all the error details, time
will be saned in the notepad .so that wecan get the notepad of
date and can see the error details.
iii. For This we need to create a folder at server side . The code for
the sameshould be in the startpage of the application .
Code to create the Folder
/// <summary>
/// fuction to createfolder andfilefor exceptionhandling
/// </summary>
privatevoid CreateErrorFolder()
{
stringerrorFolder=AppDomain.CurrentDomain.BaseDirectory +"ErrorDetails";
// Directory for thethePDF documentto be shown
DirectoryInfo directory=newDirectoryInfo(errorFolder);
try
{
if (!directory.Exists)
{
directory.Create();
}
6. }
catch (Exceptionex)
{
string msg=ex.ToString();
}
}
iv.We need to call the abovefunction in page load
protected void Page_Load(objectsender,EventArgs e)
{
CreateErrorFolder();
}
v.This will create the folder named ErrorDetails in the currentdirectory.
vi. Create one .cs file in dal transaction layer .
we need to create the .cs file in dal transaction so that we can usethat file in BLL
and Code behind of each page.sincewe give reference of DAL to BLL and BLL to
Code Behind.
Vii.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Web;
using System.Globalization;
namespace DemoDAL
{
public class ErrorHandler
{
public static void WriteError(string errorMessage)
{
try
{
string path = "~ErrorDetails" + DateTime.Today.ToString("dd-MMM-yy")
+ ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
7. using (StreamWriter w =
File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("rnStart Message : ");
w.WriteLine("{0}",
DateTime.Now.ToString(CultureInfo.InvariantCulture));
w.WriteLine("Page : " +
System.Web.HttpContext.Current.Request.Url.ToString());
w.WriteLine("nError Message: " + errorMessage);
w.WriteLine("__________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}
}
}
}
This .cs file contains the public static void WriteError(string errorMessage) function
This function will create a notepad with title of the current date ,It will take the
present time and will write the error details there .
Ex.
Start Message :
06/28/2014 18:17:57
Page : http://localhost:4766/432/Pages/Demo.aspx/PopulateDemo
Error Message: System.DivideByZeroException: Attempted to divide by zero.
at Demo.UI.Pages.HomeDemo.PopulateDemo(Int32 IDDemo) in
C:UsersDemoPagesHomeDemo.aspx.cs:line 45
Vii. In order to call the above function and pass the error
message to that function we have to write all functions in
Code behond with try… catch Blocks .
8. Ix. In the catch block,the error messageis taken and sent it to WriteError function.
Where it will be printed in notepad.
catch (Exception ex)
{
string msg = Convert.ToString(ex);
ErrorHandler.WriteError(msg);
throw ex;
}