You are on page 1of 8

Exception handling in 3-Tier Architecture - CodeProject Page 1 of 8

7,244,410 members and growing! (22,895 online) Member 2860991 Sign out

Home Articles Questions & Answers Learning Zones Jobs Features Help! Lounge

Articles / Quick Answers

Article Browse Code Stats Revisions (3) 9 4.43 / 5, 18 votes

» General Programming » Exception Handling » General


First Posted 3 Jun 2010

Exception handling in 3-Tier Views


Bookmarked
7,570
69 times
Architecture Licence CPOL

By Sohail Maroof, Farrukh Hashmi | 3 Jun 2010 | Unedited WinXP, Win2003, SQL2005,
contribution Part of The SQL Zone. VS2008, C#, ASP.NET,
Windows, SQL-Server ...

Exception handling in 3-Tier Architecture using Enterprise Library

Is your email address OK? You are signed up for our newsletters but your email address is either
unconfirmed, or has not been reconfirmed in a long time. Please click here to have a confirmation email sent so
we can confirm your email address and start sending you newsletters again. Alternatively, you can update your
subscriptions.

 Download Common - 3.21 MB

Introduction

We have been thinking to work on Exception handling in 3-Tier Architecture using Enterprise Library
since ages but never got time or get into the situation where it should have become a requirement.
Finally, we got chance to work on it.

Our main objective was to handle exceptions seamlessly in three tiered architecture. We checked
internet but couldn’t find appropriate code sample doing stuff that we wanted. Therefore, we decided to
write a re-useable code to help ourselves and others. Below is what we think, exception handling should
do:

Scenarios Description Expected Result


1 Application called a stored procedure. Happy path; everything should work fine.
Exception Raised by Database System should log the thrown exception in a sink
Management System such as Primary (Text File). Replace the Exception with a User
2
Key violated or Object does not exist friendly Message and propagate it to UI passing
etc. through the Business Logic Layer.

Based upon some certain validation Thrown Custom Error message should be

http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx 8/13/2010
Exception handling in 3-Tier Architecture - CodeProject Page 2 of 8

check / business rule a Custom Error is propagated to UI without Logging assuming these
3 raised from Stored Procedure. error messages will be some kind of alternative
flows instead of real exception.
While processing the request an error
System should log the thrown exception in a sink
occurred in Business Logic such as
4 (Text File). Replace the Exception with a User
Divide-by-zero, Object not set, Null
friendly Message and should propagate that to UI.
reference exception etc.
Thrown Custom Error message should be
Based upon some certain business
propagated to UI without Logging assuming these
5 validation check, a custom exception
error messages will be some kind of alternative
was thrown from Business Logic Layer.
flows instead of real exception.
While processing the request an error System should log the thrown exception in a sink
6 occurred in UI. For example, Null (Text File). Replace the Exception with a User
reference exception etc. friendly Message and should propagate that to UI.

Using the code

What things do you need to use/run this code?

 Microsoft.NET Framework 3.5


 Microsoft Visual Studio 2008
 Enterprise Library 5.0
 SQL Server (Server, Desktop or SQL Express Edition)

Adjust connection string accordingly.

Let us explain how this application is broken down into pieces:

 User Interface: Web Application using ASP.NET and C# as code behind


 Business Logic: We have created separate folder inside the Web Application for Business Logic
purpose. However, it can easily be moved into a separate Class Library project.
 Helpers: Windows Class Library using C#. We created this project to combine below functionality:
 Data Access Helper Class which is using Enterprise Library to interact with Database. This
way we can enjoy Enterprise Library’s power to work with any type of database management
system such as SQL and Oracle.
 Exception handling which is also using Enterprise Library to log, replace and propagate
exception using different policies.

To handle scenarios described above, following Exception Type classes are being created:

BaseException: It is a base class inherited from System.Exception class. All other classes in this
project will be inherited from this class.

Blocks of code should be set as style "Formatted" like this:

Collapse | Copy Code


using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Common.Helpers.ExceptionHandling
{
public class BaseException : System.Exception, ISerializable
{
public BaseException()
: base()
{
// Add implementation (if required)
}

public BaseException(string message)


: base(message)
{
// Add implementation (if required)
}

public BaseException(string message, System.Exception inner)


: base(message, inner)
{
// Add implementation (if required)
}

protected BaseException(SerializationInfo info, StreamingContext context)


: base(info, context)
{
// Add implementation (if required)
}
}
}

http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx 8/13/2010
Exception handling in 3-Tier Architecture - CodeProject Page 3 of 8

DataAccessException: This is used by the Exception handling Block to replace the original exception
with a User Friendly message such as “An unknown error has occurred at database level while
processing your request. Please contact Technical Help Desk with this identifier XXXXXXXXXXXXXX”.

Collapse | Copy Code


using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Common.Helpers.ExceptionHandling
{
public class DataAccessException : BaseException, ISerializable
{
public DataAccessException()
: base()
{
// Add implementation (if required)
}

public DataAccessException(string message)


: base(message)
{
// Add implemenation (if required)
}

public DataAccessException(string message, System.Exception inner)


: base(message, inner)
{
// Add implementation
}

protected DataAccessException(SerializationInfo info, StreamingContext context)


: base(info, context)
{
//Add implemenation
}

}
}

DataAccessCustomException: This is used by the Exception Handling block to send raised Custom
Error message towards UI.

PassThroughException: This is used to replace DataAccessException and DataAccessCustomException


types with this type at Business Logic level. Otherwise, Business Logic will also handle the exception as
Data access is being called from Business Logic.

BusinessLogicException: This is used by the Exception Handling block to replace the original
exception with a user friendly message such as “An unknown error has occurred in Business Logic Layer
while processing your request. Please contact Technical Help Desk with this identifier
XXXXXXXXXXXXXX”.

BusinessLogicCustomException: This is used by the Exception Handling block to send raised Custom
Error message towards UI.

UserInterfaceException: This is used by the Exception Handling block to replace the original exception
with a user friendly message such as “An unknown error has occurred at User Interface while processing
your request. Please contact Technical Help Desk with this identifier XXXXXXXXXXXXXX”

Following polices are created to support design:

DataAccessPolicy: This policy will log the original exception in defined sink will replace the original
exception with DataAccessException type.

Collapse | Copy Code


<add name="DataAccessPolicy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="DataAccessLoggingHandler" type="Microsoft.Practices.EnterpriseL
logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.Enterpr
priority="0" />
<add name="DataAccessReplaceHandler" type="Microsoft.Practices.EnterpriseL
exceptionMessage="An unknown error has occurred in Data Access Layer while processing your request. Please contract Help D
replaceExceptionType="Common.Helpers.ExceptionHandling.DataAccessException, Helpers, Version=1.0.0.0, Culture=neutral, Pub
</exceptionHandlers>
</add>
</exceptionTypes>
</add>

DataAccessCustomPolicy: This policy will only replace the original exception with

http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx 8/13/2010
Exception handling in 3-Tier Architecture - CodeProject Page 4 of 8

DataAccessCustomException type.

Collapse | Copy Code


<add name="DataAccessCustomPolicy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow">
<exceptionHandlers>
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHa
replaceExceptionType="Common.Helpers.ExceptionHandling.DataAccessCustomException, Helpers, Version=1.0.0.0, Culture=neutral, Public
</exceptionHandlers>
</add>
</exceptionTypes>
</add>

PassThroughPolicy: This policy will replace the original exceptions of type DataAccessException or
DataAccessCustomException with PassThroughException type.

Collapse | Copy Code


<add name="PassThroughPolicy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow">
<exceptionHandlers>
<add name="PassThroughReplaceHandler" type="Microsoft.Practices.EnterpriseLibrary.E
replaceExceptionType="Common.Helpers.ExceptionHandling.PassThroughException, Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyTo
</exceptionHandlers>
</add>
</exceptionTypes>
</add>

BusinessLogicPolicy: This policy will log the original exception in defined sink will replace the original
exception with BusinessLogicException type.

Collapse | Copy Code


<add name="BusinessLogicPolicy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="BusinessLogicLoggingHandler" type="Microsoft.Practices.EnterpriseLibrary
logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrar
priority="0" />
<add name="BusinessLogicReplaceHandler" type="Microsoft.Practices.EnterpriseLibrary
exceptionMessage="An unknown error has occurred in Business Logic Layer while processing your request. Please contract Help Desk Su
replaceExceptionType="Common.Helpers.ExceptionHandling.BusinessLogicException, Helpers, Version=1.0.0.0, Culture=neutral, PublicKey
</exceptionHandlers>
</add>
</exceptionTypes>
</add>

BusinessLogicCustomPolicy: This policy will only replace the original exception with
BusinessLogicCustomException type.

Collapse | Copy Code


<add name="BusinessLogicCustomPolicy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow">
<exceptionHandlers>
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHa
replaceExceptionType="Common.Helpers.ExceptionHandling.BusinessLogicCustomException, Helpers, Version=1.0.0.0, Culture=neutral, Pub
</exceptionHandlers>
</add>
</exceptionTypes>
</add>

UserInterfacePolicy: This policy will log the original exception in defined sink will replace the original
exception with UserInterfaceException type.

Collapse | Copy Code

http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx 8/13/2010
Exception handling in 3-Tier Architecture - CodeProject Page 5 of 8

<add name="UserInterfacePolicy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="UserInterfaceReplaceHandler" type="Microsoft.Practices.EnterpriseLibrary
logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrar
priority="0" />
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHa
exceptionMessage="An error occord at front end. please check."
replaceExceptionType="Common.Helpers.ExceptionHandling.UserInterfaceException, Helpers, Version=1.0.0.0, Culture=neutral, PublicKey
</exceptionHandlers>
</add>
</exceptionTypes>
</add>

Following exception handlers are being created to manage exception logging, replacement and
propagating:

DataAccessExceptionHandler: This handler will take care of "DataAccessException" and


"DataAccessCustomException" exception types. Based upon the type of the exception, this handler will
decide which policy should work. Below is the code calling different policy:

Collapse | Copy Code


using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace Common.Helpers.ExceptionHandling
{
public static class DataAccessExceptionHandler
{
public static bool HandleException(ref System.Exception ex)
{
bool rethrow = false;
if ((ex is SqlException))
{
SqlException dbExp = (SqlException)ex;
if (dbExp.Number >= 50000)
{
rethrow = ExceptionPolicy.HandleException(ex, "DataAccessCustomPolicy");
ex = new DataAccessCustomException(ex.Message);
}
else
{
rethrow = ExceptionPolicy.HandleException(ex, "DataAccessPolicy");
if (rethrow)
{
throw ex;
}
}
}
else if (ex is System.Exception)
{
rethrow = ExceptionPolicy.HandleException(ex, "DataAccessPolicy");
if (rethrow)
{
throw ex;
}
}
return rethrow;
}
}
}

BusinessLogicExceptionHandler: This handler will take care of “PassThroughException”,


“BusinessLogicException” and “BusinessLogicCustomException” exception types. Based upon the type of
the exception, this handler will decide which policy should work. Below is the code calling different
policy:

Collapse | Copy Code

http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx 8/13/2010
Exception handling in 3-Tier Architecture - CodeProject Page 6 of 8

using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Common.Helpers.ExceptionHandling;

namespace Common.Helpers.ExceptionHandling
{
public static class BusinessLogicExceptionHandler
{
public static bool HandleExcetion(ref System.Exception ex)
{
bool rethrow = false;
if ((ex is DataAccessException) || (ex is DataAccessCustomException))
{
rethrow = ExceptionPolicy.HandleException(ex, "PassThroughPolicy");
ex = new PassThroughException(ex.Message);
}
else if (ex is BusinessLogicCustomException)
{
rethrow = ExceptionPolicy.HandleException(ex, "BusinessLogicCustomPolicy");
}
else
{
rethrow = ExceptionPolicy.HandleException(ex, "BusinessLogicPolicy");
}
if (rethrow)
{
throw ex;
}
return rethrow;
}

}
}

If you examine the above code, you will see that in case of DataAccessException or
DataAccessCustomException, this handler is using PassThroughExceptionPolicy. Means, exception has
already been logged it needs to be propagated towards caller. Afterwards, system is checking whether
exception is raised intentionally by the Business Logic Layer or it is a uncontrolled exception. Based
upon type handler is calling appropriate Exception Handling Policy.

UserInterfaceExceptionHandler: This handler will take care of “UserInterfaceException” exception


type. Based upon the type of the exception, this handler will decide which policy should work. Below is
the code calling different policy:

Collapse | Copy Code


using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace Common.Helpers.ExceptionHandling
{
public static class UserInterfaceExceptionHandler
{

public static bool HandleExcetion(ref System.Exception ex)


{
bool rethrow = false;
try
{
if (ex is BaseException)
{
// do nothing as Data Access or Business Logic exception has already been logged / handled
}
else
{
rethrow = ExceptionPolicy.HandleException(ex, "UserInterfacePolicy");
}
}
catch (Exception exp)
{
ex = exp;
}
return rethrow;
}
}
}

That's it. Download the code and enjoy and do leave your feedback.

Thank!
Sohail Maroof Naushahi, Farrukh Hashmi

http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx 8/13/2010
Exception handling in 3-Tier Architecture - CodeProject Page 7 of 8

License Sponsored Links


$4.95/month ASP.NET Web Hosting
This article, along with any associated source code and files, is licensed under The Code Project Open ASP.NET 4 Web Hosting w/MS SQL
License (CPOL) 2008 Included!...
www.winhost.com
About the Authors Resco MobileForms Toolkit
The richest, most complete and
Sohail Maroof award winning...
www.resco.net

UIControlSuite .NET
32 powerful .NET controls for
WinForms, WPF,...
United States www.binarymission.co.uk

Member

Farrukh Hashmi

See Also...
Creating Custom Controls
United States An introduction to creating custom
controls...
Member HTML 4.01 Programmer's Reference -
Chapter 1: Introduction
Using the <object> tag to embed
Article Top Rate this article for us! Poor Excellent Vote
functionality...

XSLT Programmer's Reference 2nd


Edition
This chapter is about the purpose of
XSLT and...

Summer 2004 NYC CPian Get


Comments and Discussions Together
An article on a NYC get together

FAQ Search Multi-tier Enterprise Application


Architecture
Noise Tolerance Medium Layout Normal Per page 25 Update Multi-tier Enterprise Application
Architecture
New Message Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh) First Prev Next

Great izhangronghua 0:57 15 Jul '10


Announcements
Re: Great Sohail Maroof 4:40 15 Jul '10
Write an Android Tutorial, Win
Very good article Aazee 2:53 15 Jun '10 a Droid X!

Winform Implementation? hat_master 8:58 8 Jun '10 Have an app on Windows


Azure? Win a laptop!
Re: Winform Implementation? Sohail Maroof 11:37 9 Jun '10
Monthly Competition
Re: Winform Implementation? hat_master 10:04 15 Jun '10

Re: Winform Implementation? Sohail Maroof 15:47 15 Jun '10


The Daily Insider
Good article Donsw 6:16 4 Jun '10
A 40-year-old computer demo that
Re: Good article Farrukh Hashmi 9:51 4 Jun '10
still amazes
Last Visit: 21:00 31 Dec '99 Last Update: 3:50 13 Aug '10 1 Daily News: Signup now.

General News Question Answer Joke Rant Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+PgUp/PgDown to switch pages.

PermaLink | Privacy | Terms of Use Copyright 2010 by Sohail Maroof, Farrukh Hashmi
Last Updated: 3 Jun 2010 Everything else Copyright © CodeProject, 1999-2010
Web21 | Advertise on the Code Project

http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx 8/13/2010
Exception handling in 3-Tier Architecture - CodeProject Page 8 of 8

http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx 8/13/2010

You might also like