MemoryStreamおよびGZipStreamクラスを使用して文字列をバイト配列に圧縮および解凍するAPI クラスがあります。
これら 2 つのクラスを使用すると、多くの例外がスローされる可能性があり、API でスローされた例外を処理する最良の方法は何か疑問に思っていました。この場合、独自のカスタム例外で各例外をラップする方がよいでしょうか、それとも呼び出し元のコードで個々の例外をキャプチャする方がよいでしょうか?
これは、この特定のユース ケースに限定されるものではなく、一般的な例外処理のベスト プラクティスに関する質問だと思います。
/// <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);
}
}
これは、基本例外のキャッチに関する良い投稿です。