错误处理(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”解决方法
随机推荐
- 算法训练 Cowboys(DP)
问题描述 一个间不容发的时刻:n个牛仔站立于一个环中,并且每个牛仔都用左轮手枪指着他旁边的人!每个牛仔指着他顺时针或者逆时针方向上的相邻的人.正如很多西部片那样,在这一刻,绳命是入刺的不可惜……对峙的 ...
- OpenCV自带dnn的Example研究(6)— text_detection
这个博客系列,简单来说,今天我们就是要研究 https://docs.opencv.org/master/examples.html下的 6个文件,看看在最新的OpenCV中,它们是如何发挥作用的. ...
- new types may not be defined in a return type(c++语言编译错误,处理)
在写程序的时候,定义类时要在大括号后面加上: class Point{ public: Point(int a,int b); Point(const Point &p); int getx( ...
- 洛谷 P3586 [POI2015]LOG
P3586 [POI2015]LOG 题目描述 维护一个长度为n的序列,一开始都是0,支持以下两种操作:1.U k a 将序列中第k个数修改为a.2.Z c s 在这个序列上,每次选出c个正数,并将它 ...
- oracle修改连接数
使用 sqlplus登陆 sqlplus system 然后切换到sysdba模式 conn ?/ as sysdba 查询当前的processes sessions的大小 show ...
- 老男孩Day8作业:FTP
1.作业需求 开发简单的FTP: 1. 用户登陆 2. 上传/下载文件 3. 不同用户家目录不同 4. 查看当前目录下文件 5. 充分使用面向对象知识 2.流程图 3.目录结构 4.代码区 bin目录 ...
- 剑指offer —— 从尾到头打印链表
1.问题:输入一个链表,从尾到头打印链表每个节点的值. /** * public class ListNode { * int val; * ListNode next = null; * * Lis ...
- git相关问题处理
1.在git push时无法提交代码,相对于git服务器上,本身代码可能不是最新的,因此提交的时候会报以下这个错误 Updates were rejected because the tip of y ...
- kuangbin专题十二 POJ1661 Help Jimmy (dp)
Help Jimmy Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 14214 Accepted: 4729 Descr ...
- vue.js组件之j间的通讯四,通过单一事件来管理组件通讯
总结; 首先需要创建是一个空实例: var vm = new Vue(); vm.$emit(事件,数据); vm.$on(事件,function(data){ }bind(this))