Skip to content

Instantly share code, notes, and snippets.

@wolf99
Last active August 3, 2017 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/85f9ca4d41258cc1f970800dbde6555d to your computer and use it in GitHub Desktop.
Save wolf99/85f9ca4d41258cc1f970800dbde6555d to your computer and use it in GitHub Desktop.
A boilerplate C# exception class
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace FooProgram
{
// Recommended practice to derive from Exception rather than ApplicationException
// Recommended practice to make exceptions serializable
[Serializable]
public class BoilerplateException : Exception, ISerializable
{
// Recommended minimum constructors
public BoilerplateException() { }
public BoilerplateException(string message)
: base(message) { }
public BoilerplateException(string message, string bar)
: base(message)
{
Bar = bar;
}
// Custom fields, properties and constructors
private const string DefaultExceptionMessage =
"Default exception message"
public string Bar { get; set; }
public BoilerplateException(string bar)
: base(DefaultExceptionMessage)
{
Bar = bar;
}
public BoilerplateException(
string message, Exception innerException)
: base(message, innerException) { }
public BoilerplateException(
string message, string bar, Exception innerException)
: base(message, innerException)
{
Bar = bar;
}
// Recommended method to customize the serialization process
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(
SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
base.GetObjectData(info, context);
info.AddValue(nameof(Bar), Bar);
// or
//info.AddValue(nameof(Bar), Bar, Bar.GetType());
}
// Recommended constructor to customize the deserialization process
protected BoilerplateException(
SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Bar = info.GetString(nameof(Bar));
// or
//Bar = (string)info.GetValue(nameof(Bar), Bar.GetType());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment