错误处理(Operation Result)方法
自己开发的公众号,可以领取淘宝内部优惠券

问题
现在有一个FileStorageService类,继承自IStorageService,具体实现如下
public interface IStorageService
{
void WriteAllBytes(string path, byte[] buffer);
byte[] ReadAllBytes(string path);
} public class FileStorageService : IStorageService
{
public void WriteAllBytes(string path, byte[] buffer) {
File.WriteAllBytes(path, buffer);
} public byte[] ReadAllBytes(string path)
{
return File.ReadAllBytes(path);
}
}
假设调用其中任一一个方法出现异常,例如读写文件时候经常碰见的异常:IOException, DirectoryNotFoundException, FileNotFoundException,UnauthorizedAccessException… 甚至是 OutOfMemoryException
方案1-不是我的问题
IStorageService 不关心抛出的异常,那是使用者的职责。如此便将问题抛给了使用IStorageService接口的用户,它们必须要捕获有可能抛出的异常,往往一种偷懒的做法就是使用try catch语句将其包裹起来,如:
IStorageService myStorageService = Resolver.Resolve<IStorageService>();
try
{
myStorageService.ReadAllBytes("C:\stuff.data");
} catch (Exception exception)
{
// please don't write generic error messages like this, be specific
Logger.Log("Oops something went wrong: " + exception.Message);
}
catch exception并不是什么好主意,而且每次调用都需要使用try catch很不方便
方案2-创建新的异常类
一种改进的方法就是创建我们自己的异常类如StorageReadException,不管以后具体的实现如何变化,我们仅捕获特定的异常来进行异常处理
public class StorageReadException : Exception
{
public StorageReadException(Exception innerException)
: base(innerException.Message, innerException)
{
}
}
之前的FileStorageService实现更改为:
public byte[] ReadAllBytes(string path)
{
try
{
return File.ReadAllBytes(path);
}
catch (FileNotFoundException fileNotFoundException)
{
throw new StorageReadException(fileNotFoundException);
}
}
调用代码:
IStorageService myStorageService = Resolver.Resolve<IStorageService>();
try
{
myStorageService.ReadAllBytes(path);
}
catch (StorageReadException sre)
{
Logger.Log(String.Format("Failed to read file from path, {0}: {1}", path, sre.Message));
}
同样存在try catch 包裹问题,而且用户必须依赖一个新的异常类型
方案3-Try 模式并返回一个Complex Result
我们可以使用Try模式来避免用户使用try catch,Try模式类似C#里int方法
bool TryParse(string s, out int result),我们对接口进行更改
byte[] ReadAllBytes(string path)
变为
bool TryReadAllBytes(string path, out byte[] result)
但是这样不能提供用户更多的错误信息。如果我们想要显示更多的有帮助的异常信息给用户,可以返回一个通用的结果类OperationResult<TResult>
public class OperationResult<TResult>
{
private OperationResult ()
{
} public bool Success { get; private set; }
public TResult Result { get; private set; }
public string NonSuccessMessage { get; private set; }
public Exception Exception { get; private set; } public static OperationResult<TResult> CreateSuccessResult(TResult result)
{
return new OperationResult<TResult> { Success = true, Result = result};
} public static OperationResult<TResult> CreateFailure(string nonSuccessMessage)
{
return new OperationResult<TResult> { Success = false, NonSuccessMessage = nonSuccessMessage};
} public static OperationResult<TResult> CreateFailure(Exception ex)
{
return new OperationResult<TResult>
{
Success = false,
NonSuccessMessage = String.Format("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace),
Exception = ex
};
}
}
FileStorageService的ReadAllBytes 方法变为
public OperationResult<byte[]> TryReadAllBytes(string path)
{
try
{
var bytes = File.ReadAllBytes(path);
return OperationResult<byte[]>.CreateSuccessResult(bytes);
}
catch (FileNotFoundException fileNotFoundException)
{
return OperationResult<byte[]>.CreateFailure(fileNotFoundException);
}
}
调用代码:
var result = myStorageService.TryReadAllBytes(path);
if(result.Success)
{
// do something
}
else
{
Logger.Log(String.Format("Failed to read file from path, {0}: {1}", path, result.NonSuccessMessage));
}
原文:Error Handling in SOLID C# .NET – The Operation Result Approach
错误处理(Operation Result)方法的更多相关文章
- InnoDB: Operating system error number 87 in a file operation. 错误87的解决方法
InnoDB: Operating system error number 87 in a file operation. 错误87的解决方法 140628 8:10:48 [Note] Plugi ...
- coreseek常见错误原因及解决方法
coreseek常见错误原因及解决方法 Coreseek 中文全文检索引擎 Coreseek 是一款中文全文检索/搜索软件,以GPLv2许可协议开源发布,基于Sphinx研发并独立发布,专攻中文搜索和 ...
- android 真机调试出现错误 INSTALL_FAILED_INSUFFICIENT_STORAGE 的解决方法。
关于这个神奇的 内存不够错误的通常解决方法,网上大把,建议大家在尝试过了网上的方法后再来尝试下我的这种方法. 编译工具: android studio 测试真机:米 2 调试的时候出现:INSTALL ...
- 无法打开物理文件xxx.mdf操作系统错误 5:“5(拒绝访问。)” (Microsoft SQL Server,错误: 5120)的解决方法
无法打开物理文件xxx.mdf操作系统错误 5:“5(拒绝访问.)” (Microsoft SQL Server,错误: 5120)的解决方法 问题描述: 在附加数据库到sql server时,附 ...
- 错误:Unsupported major.minor version 51.0(jdk版本错误)的解决方法
错误:Unsupported major.minor version 51.0(jdk版本错误)的解决方法 java.lang.UnsupportedClassVersionError: org/ap ...
- 批处理命令篇--配置免安装mysql 5.6.22, 以及1067错误的一个解决方法
mysql 服务启动出现1067错误的一个解决方法: 当服务启动出现1067错误时,可查看“windows 事件查看器”,发现类似错误提示 Can't find messagefile 'F:\ ...
- IIS发布网站浏览之后看到的是文件目录 & Internal Server Error 处理程序“ExtensionlessUrlHandler-ISAPI-4.0_64bit”在其模块列表中有一个错误模块“IsapiModule” 解决方法 & App_global.asax.pduxejp_.dll”--“拒绝访问。 ”
Q:IIS发布网站浏览之后看到的是文件目录 A:它出现了一个说到.NET4.0 更高框架什么的错误,所以我将 .NTE CRL版本由4.0改为2.0了,改为2.0后就出现了只能浏览文件目录了.改为4. ...
- ORA-04091错误原因与解决方法
最近工作中写了一触发器报错:ORA-04091:table XX is mutating, trigger/function may not see it. 下面通过官方文档及网友提供资料分析一下错 ...
- Eclipse进度条出现“Remote System Explorer Operation”解决方法
Eclipse进度条出现“Remote System Explorer Operation”解决方法
随机推荐
- P与NP问题详解
P,NP,NPC问题,这或许是众多OIer最大的误区之一. 本文就为大家详细讲解如上三个问题. 前序: 你会经常看到网上出现“这怎么做,这不是NP问题吗”.“这个只有搜了,这已经被证明是NP问题了”之 ...
- 生成全局唯一ID
在实际业务处理中,有时需要生成全局唯一ID来区别同类型的不同事物,介绍一下几种方式及其C++实现 //获取全局唯一ID //server_id为服务的id,因当同一个服务部署在多个服务器上时,需要区别 ...
- centoOS下安装python3 和 pip: command not found
在更新python3的时候会自动安装pip3,但是安装完成后,pip -V发现出错:command not found,找了好久,发现在建立软连接的时候路径写错了. 总结一下安装python3和发现p ...
- vue框架搭建的详细步骤之项目结构(二)
上一篇中简单的创建了一个脚手架,这篇简单的讲一下脚手架的项目结构: (1).build/ 此目录包含开发服务器和生产webpack构建的实际配置.通常,您不需要触摸这些文件,除非您要自定义We ...
- loj #2008. 「SCOI2015」小凸想跑步
#2008. 「SCOI2015」小凸想跑步 题目描述 小凸晚上喜欢到操场跑步,今天他跑完两圈之后,他玩起了这样一个游戏. 操场是个凸 n nn 边形,N NN 个顶点按照逆时针从 0∼n−1 0 ...
- 10.6-10.7 牛客网NOIP模拟赛题解
留个坑... upd:估计这个坑补不了了 如果还补不了就删了吧
- Leetcode 121. Best Time to Buy and Sell Stock 最佳股票售卖时(动态规划,数组,模拟)
题目描述 已知一个数组,第i个元素表示第i天股票的价格,你只能进行一次交易(买卖各一次),设计算法找出最大收益 测试样例 Input: [7, 1, 5, 3, 6, 4] Output: 5 最大收 ...
- 在Mvc中,ExpandoObjec类的使用
创建一个基本mvc项目 1.向Models目录下添加一个类文件MyModel.cs文件,代码如下: using System; using System.Collections.Generic; us ...
- P3167 [CQOI2014]通配符匹配 题解
题目 题目大意 给出一个字符串,其中包含两种通配符 ‘?’和 ‘*’ ,‘?’可以代替一个字符,‘*’可以代替一个字符串(长度可以为0) 然后给出几个字符转,判断能否用给出的字符串表示出来 样例解释 ...
- vue学习三:生命周期钩子
生命周期钩子介绍: 每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听.编译模板.将实例挂载到 DOM 并在数据变化时更新 DOM 等.同时在这个过程中也会运行一些叫做生 ...