I have a API class using the MemoryStream and GZipStream classes to compress and decompress a string to a byte array.
Using these two classes a number of exceptions may be throws and I was wondering what is the best method of handling thrown exception for an API. In this case would it be be better to wrap each of the exception with my own Custom Exception or would it be preferable to capture each individual exception in the calling code?
I suppose this is a question that is not limited to this particular use case but more about general exception handling best practices.
/// <summary>
/// Compress the string using the SharpLibZip GZip compression routines
/// </summary>
/// <param name="s">String object to compress</param>
/// <returns>A GZip compressed byte array of the passed in string</returns>
/// <exception cref="Helper.Core.Compression.StringCompressionException">Throw when the compression memory stream fails </exception>
/// <exception cref="System.ArgumentNullException">Throw when string parameter is Null</exception>
/// <exception cref="System.ArgumentException">Throw when the string parameter is empty</exception>
public async Task<byte[]> CompressStringAsync(string s)
{
if (s == null) throw new ArgumentNullException("s");
if (string.IsNullOrWhiteSpace(s)) throw new ArgumentException("s");
byte[] compressed = null;
try
{
using (MemoryStream outStream = new MemoryStream())
{
using (GZipStream tinyStream = new GZipStream(outStream,CompressionMode.Compress))
{
using (MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(s)))
{
await memStream.CopyToAsync(tinyStream);
}
}
compressed = outStream.ToArray();
}
return compressed;
}
catch (ArgumentNullException ex)
{
throw new StringCompressionException("Argument Was Null", ex);
}
catch (EncoderFallbackException ex)
{
throw new StringCompressionException("Stream Encoding Failure", ex);
}
catch (ArgumentException ex)
{
throw new StringCompressionException("Argument Was Not Valid", ex);
}
catch (ObjectDisposedException ex)
{
throw new StringCompressionException("A Stream Was Disposed", ex);
}
catch (NotSupportedException ex)
{
throw new StringCompressionException("Action Was Not Supported", ex);
}
}
Here is a good post on catching base exceptions.