错误处理(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”解决方法
随机推荐
- eclipse 链接 hadoop - 问题
问题:在没有联网时可以连接,当联网时无法链接hdfs 解决:重启hadoop各种守护进程 解析:因该跟host文件中有映射ip有关,有待继续解决......(先留个底)
- 【转】新建网站(CodeFile)与新建Web应用(Codebehind)的区别
源地址:http://www.cnblogs.com/harry0906/articles/3575725.html
- Error: connection reset by peer ,during filebeat connect to elk.
Error screenshot like below: Reason: What I found that was the machine failing had same configuratio ...
- HTTP,HTTPS端口号
博主暂做个笔记,查询资料再纠正~~~~小白不要不假思索的抄走~~~ 一般情况下,HTTP默认工作端口是8000,HTTPS默认工作端口是443
- git相关问题处理
1.在git push时无法提交代码,相对于git服务器上,本身代码可能不是最新的,因此提交的时候会报以下这个错误 Updates were rejected because the tip of y ...
- socket 释放全过程
1.close()函数:立即返回到进程 int close(int sockfd); //返回成功为0,出错为-1. close 一个套接字的默认行为是把套接字标记为已关闭,然后立即返回到调用 ...
- 利用zookeeper生成唯一id
package com.cxy.com.cxy.curator; import java.util.concurrent.ExecutorService; import java.util.concu ...
- SprimgMVC学习笔记(一)—— SpringMVC入门
一.什么是 SpringMVC ? 在介绍什么是 SpringMVC 之前,我们先看看 Spring 的基本架构.如下图: 我们可以看到,在 Spring 的基本架构中,红色圈起来的 Spring W ...
- Hdu 5862 Counting Intersections(有n条线段,每一条线段都是平行于x轴或者y轴,问有多少个交点+树状数组区间求和单点跟新)
传送门:Hdu 5862 Counting Intersections 题意:有n条线段,每一条线段都是平行于x轴或者y轴,问有多少个交点 分析: 基本的操作流程是:先将所有的线段按照横树坐标x按小的 ...
- 面向对象之-------------------永不停机的ATM
import os class Account: def __init__(self, username, password, money=0): self.username = username s ...