Click here to Skip to main content
13,145,774 members (61,612 online)
Click here to Skip to main content
Add your own
alternative version


10 bookmarked
Posted 23 Nov 2013

Exception Handling Using Custom Attributes and Stacktrace

, 25 Nov 2013
Rate this:
Please Sign up or sign in to vote.
Exception handling using custom attributes and stacktrace.


Exception handling is a very important part in every application. It should tell the proper message to the end user; so that they can explain to the supporting team properly. It will be very helpful to identify and resolve the issue quickly. 


I was filling one application form then I submitted it. But it prompted one generic message that 'There is a technical issue, you can not precede further, please contact administrator'. I do not understand what the exact problem is. If the application prompted an actual message, I could have understood. So I developed a small utility which generates the actual failure message using stacktrace and custom attribute. Here, we do not need to implement try catch block for all the methods.

To implement this approach, we need to place a custom attribute on top of all the methods and it should describe what the method actually does so that we can generate message for each step while exception occurred.

Where we can use

Since this utility extract the method description from the entire StackTrace, it will disclose the business flow to the end user. It is not required and it may be a loophole for hackers; so that this approach will be helpful for in-house tool where performing complex algorithms also if you do not want to disclose any action, we no need to specify the description for the particular method.

Known issue

In release build we cannot have all the steps. If you really required all the steps, we can get it by changing the build configuration settings.

  • Project-> Properties -> Build
  • Configuration = Release
  • Optimized Code = false (unchecked)
  • Advanced build settings: Debug Info: full

Source Code

The main application is as follows:

class Program
    static void Main(string[] args)
            var loanValidator = new LoanValidator();
        catch (Exception ex)
            string exceptionMessage=ExceptionHelper.GetDetailMessage(ex);

The output is as given below:

Sample Image

Custom Attribute source code is as follows:

public class MethodDescription : Attribute
    public MethodDescription(string description)
        this.Description = description;
    public string Description { get; set; }

Loan validator source code is given below:

public class LoanValidator
    [MethodDescription("Validating loan application")]
    public bool CheckLoanApplication()
        bool isValidPersonalDetail = CheckPersonalDetail();
        bool isValidEmploymentDetail = CheckEmploymentDetail();
        bool isValidBankAccountDetail = CheckBankAccountDetail();

        if (isValidPersonalDetail && 
        isValidEmploymentDetail && isValidBankAccountDetail)
            return true;
            return false;

    [MethodDescription("Checking personal detail")]
    private bool CheckPersonalDetail()
        return true;

    [MethodDescription("Checking employment detail")]
    private bool CheckEmploymentDetail()
        return true;
    [MethodDescription("Checking bank account detail")]
    private bool CheckBankAccountDetail()
        return true;

    [MethodDescription("Checking outstanding detail from common web server")]
    private bool CheckAnyOutstanding()
        throw new WebException();
        return true;

Exception handler helper source code is shown below:

public class ExceptionHelper
    /// <summary>
    /// Frame the detail message from exception
    /// </summary>
    /// <param name="ex"></param>
    /// <returns></returns>
    public static string GetDetailMessage(Exception ex)
        StringBuilder messageBuilder = new StringBuilder();
        Type attributeType = typeof(MethodDescription);            
        int step = 1;

        var attributes = GetStackTraceSteps<MethodDescription>(ex);
        if(attributes!=null && attributes.Count>0)
        ("Sorry there is a problem while processing step {0}:",attributes.Count));
        foreach (var attribute in attributes)
            ("Step {0}: {1}", step.ToString(), attribute.Description));

        string formatedMessage = string.Format("{0}Error Description : {1}",

        return formatedMessage;

    /// <summary>
    /// Extrace the custom attribute details from the stacktrace
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="ex"></param>
    /// <returns></returns>
    public static List<T> GetStackTraceSteps<T>(Exception ex)
        List<T> traceSteps = new List<T>();
        Type attributeType = typeof(T);
        StackTrace st = new StackTrace(ex);
        if (st != null && st.FrameCount > 0)

            for (int index = st.FrameCount - 1; index >= 0; index--)
                var attribute = st.GetFrame(index).
                GetMethod().GetCustomAttributes(attributeType, false).FirstOrDefault();
                if (attribute != null)


        return traceSteps;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Balachandar Jeganathan
Software Developer (Senior) cognizant
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionPerformance Pin
FatCatProgrammer10-Jan-14 5:07
memberFatCatProgrammer10-Jan-14 5:07 
QuestionThanks for this Pin
Jared Leonard2-Dec-13 8:34
memberJared Leonard2-Dec-13 8:34 
AnswerRe: Thanks for this Pin
Bala Chandar2-Dec-13 13:34
memberBala Chandar2-Dec-13 13:34 
GeneralFor certain use-cases only Pin
John Brett24-Nov-13 23:35
memberJohn Brett24-Nov-13 23:35 
GeneralRe: For certain use-cases only Pin
Bala Chandar25-Nov-13 2:36
memberBala Chandar25-Nov-13 2:36 
QuestionProblems Pin
Alois Kraus23-Nov-13 20:27
memberAlois Kraus23-Nov-13 20:27 
AnswerRe: Problems Pin
Bala Chandar25-Nov-13 2:29
memberBala Chandar25-Nov-13 2:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 25 Nov 2013
Article Copyright 2013 by Balachandar Jeganathan
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid