先贴出来代码
项目中有个页面,用来支付回调。窗体里无任何html元素。服务端程序Page_Load如下,即获取到请求的订单,校验订单是否有效,然后持久化订单数据,并回写处理成功或失败的标识:
/// <summary>
/// 由PayAndRefund/RefundForm.aspx请求过来,处理业务系统的退款请求
/// </summary>
public partial class RefundForm : System.Web.UI.Page
{
private AlipayPaymentBLL.AlipayBLL obll = new AlipayPaymentBLL.AlipayBLL();
private AlipayPaymentBLL.AlipayRefundRecord alipayRefundBll = new AlipayPaymentBLL.AlipayRefundRecord();
protected void Page_Load(object sender, EventArgs e)
{
// 记录日志和相关标记
CommonUtils.LogCommon.instance.writePay(this, "===================================================================================");
string sMsg = UrlInfo.Initial(Request).GetMsg();
CommonUtils.LogCommon.instance.writePay(this, sMsg);
ReturnValue result;
try
{
string reqStr = WebCommon.ReadStreamReqStr(Request, System.Text.Encoding.UTF8);//获得流 序列化
var refundApply = JsonConvert.DeserializeObject<CommonModel.Domains.RefundApplyDTO>(reqStr);
if (refundApply == null)
{
result = new ReturnValue("9999", "无通知参数");
}
else
{
var dt = new DataTable();
var listOrderNo = new List<string>();
var dicMoney = new Dictionary<string, string>();
var dicRemark = new Dictionary<string, string>();
result = alipayRefundBll.BuilderArray(listOrderNo, dicMoney, dicRemark, refundApply);//解析传入参数信息
if (result.Code == "0000")
{
result = new AlipayPaymentBLL.AlipayRefundRecord().CheckRefundRecordOrder(listOrderNo, refundApply);
if (result.Code == "0000")
{
result = alipayRefundBll.DoRefund(refundApply, dt, listOrderNo, dicMoney, dicRemark);
if (result.Code == "0000")
{
dt.Columns.Remove("trade_no");
string[] sTableColumName = CommonModel.CommonFun.GetColumNameOfDataTable(dt);
// 将退款数据批量insert到dbo.T_AlipayRefundRecord
// 支付宝退款是有密的,这里只保存。 在单独的支付宝退款页做跳转到支付宝输入密码进行退款操作
bool bResult = alipayRefundBll.BulkCopy(dt, sTableColumName);
result = bResult ? new ReturnValue("0000", "支付宝退款请求支付中心已收到!") : new ReturnValue("9999", "退款信息入库失败!");
}
}
}
}
}
catch (Exception ex)
{
CommonUtils.LogCommon.instance.writePay(this, "支付宝退款发起异常==>" + ex);
result = new ReturnValue("9999", "支付宝退款发起异常");
}
string jsonStr = JsonConvert.SerializeObject(result);
CommonUtils.LogCommon.instance.writePay(this, "支付宝退款返回值==>" + jsonStr);
Response.Write(jsonStr);
}
}
代码分析
不考虑逻辑,仅从代码简洁的角度来看,如上代码段存在如下问题,使得代码有了坏味道(bad smell):
- 对象oReturnValue被重复赋值并使用
- 层层嵌套, if和try...catch使得代码嵌套了好多层
代码重构
从如下几个角度进行重构:
- 引入自定义异常, 当判断失败时,返回自定义异常。这样可以去掉很多if的嵌套。
- 要对捕获到的自定义异常做处理
重构后:
/// <summary>
/// 由PayAndRefund/RefundForm.aspx请求过来,处理业务系统的退款请求
/// </summary>
public partial class RefundForm : System.Web.UI.Page
{
private AlipayPaymentBLL.AlipayBLL obll = new AlipayPaymentBLL.AlipayBLL();
private AlipayPaymentBLL.AlipayRefundRecord alipayRefundBll = new AlipayPaymentBLL.AlipayRefundRecord();
protected void Page_Load(object sender, EventArgs e)
{
// 记录日志和相关标记
CommonUtils.LogCommon.instance.writePay(this, "===================================================================================");
string sMsg = UrlInfo.Initial(Request).GetMsg();
CommonUtils.LogCommon.instance.writePay(this, sMsg);
ReturnValue result;
try
{
string reqStr = WebCommon.ReadStreamReqStr(Request, System.Text.Encoding.UTF8);//获得流 序列化
var refundApply = JsonConvert.DeserializeObject<CommonModel.Domains.RefundApplyDTO>(reqStr);
if (refundApply == null)
{
throw new ResponseErrorException("无通知参数");
}
if (alipayRefundBll.RefundOrderExists(refundApply.OrderNo))
{
throw new ResponseErrorException("支付宝退款请求订单号:" + refundApply.OrderNo + "已提交支付中心,请不要重复提交!");
}
var dt = alipayRefundBll.DoRefund1(refundApply);
dt.Columns.Remove("trade_no");
// 将退款数据批量insert到dbo.T_AlipayRefundRecord
// 支付宝退款是有密的,这里只保存。 在单独的支付宝退款页做跳转到支付宝输入密码进行退款操作
bool saveSuccess = alipayRefundBll.BulkCopy(dt);
result = saveSuccess ? new ReturnValue("0000", "支付宝退款请求支付中心已收到!") : new ReturnValue("9999", "退款信息入库失败!");
}
catch (Exception ex)
{
if (ex is ResponseErrorException)
{
result = new ReturnValue("9999", ex.Message);
}
else
{
CommonUtils.LogCommon.instance.writePay(this, "支付宝退款发起异常==>" + ex.ToString());
result = new ReturnValue("9999", "支付宝退款发起异常");
}
}
string jsonStr = JsonConvert.SerializeObject(result);
CommonUtils.LogCommon.instance.writePay(this, "支付宝退款返回值==>" + jsonStr);
Response.Write(jsonStr);
}
}
可见,代码清晰了很多。主要的方式是引入了自定义异常ResponseErrorException,使得方法只管返回理想情况下应该返回的参数类型,而现实很骨感,所以,当不满足判断条件时,就通过抛出自定义异常的方式来实现,同时也没有破坏方法的结构。 另外,我将异常捕获统一放到了主方法ProcessRequest里,也使得代码结构清晰,少了那些if的判断,是不是很漂亮?
public class ResponseErrorException : System.Exception
{
//
// 摘要:
// 使用指定的错误消息初始化 ResponseErrorException 类的新实例。
//
// 参数:
// message:
// 描述错误的消息。
public ResponseErrorException(string message) : base(message) { }
//
// 摘要: 使用指定的错误消息初始化 ResponseErrorException 类的新实例
//
// 参数:
// format:
// 复合格式字符串。
//
// args:
// 一个对象数组,其中包含零个或多个要设置格式的对象。
//
// 异常:
// System.ArgumentNullException:
// format 或 args 为 null。
//
// System.FormatException:
// format 无效。- 或 -格式项的索引小于零或大于等于 args 数组的长度。
public ResponseErrorException(string format, params object[] args)
: base(FormatString(format, args)) { }
static string FormatString(string format, params object[] args)
{
try
{
string message = string.Format(format, args);
return message;
}
catch (FormatException ex)
{
//LogHelper.Write("执行string.Format时(内容:\"{0}\",参数个数:{1})出现格式异常:{2}", format, args.Length, ex.Message);
return string.Empty;
}
}
}