Tuesday, June 17, 2014

Create Custom Exception

Create Custom exception
public class PYException : Exception
{
 public List<PYResult> PYResults { getset;}  //attribute

 public PYException() { }  // Default Constroctor

 public PYException(string message) : base(message) { } //like Application Exception

public PYException(string message, List<PYResult> pyResults): base(message)
        {
          this.PYResults = pyResults;
        }  //Application Exception with A List of Info , message usually is header.

 public PYException(string message, Exception inner) : base(message, inner) { }

 public PYException(string message, List<PYResult> pyResults, Exception inner)
        : base(message, inner)
        {
            this.ValidationResults = validationResults;
        }
}

Create exception class

[DataContract]
public class PYResult
{
  [DataMember]
  public ComponentsType ComponentType { get; set; }

  [DataMember]
  public string key { get; set; }

  [DataMember]
  public string Message { get; set; }
}


HOW TO THROW THIS ?

Use IF ELSE statement to create a exception class.

List<PYResult> pyResults = new List<PYResult>();

pyResults.Add(new PYResult ()
{
Message = String.Format("The Country cannot be selected for {0}. The country .",country.CountryName),
  key = CountryID.ToString(),
  ComponentType = PYComponentsType.Country
});


Use count to throw the exception

if (pyResults.Count() > 0)
  throw new PYException ("Updating errors. Please see the error detail",pyResults);

No comments:

Post a Comment