我有一个 API 类,它使用MemoryStream和GZipStream类将字符串压缩和解压缩为字节数组。
使用这两个类可能会抛出许多异常,我想知道处理 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);
}
}
这是一篇关于捕获基本异常的好帖子。