我已阅读有关例外,错误,错误代码等各种主题。 我通过stackoverflow的问题搜索了一个答案,但我仍然有一些误解...... 因此,在阅读我的问题时,请让我们更多地考虑为客户提供更好的结果,而不是遵循可能在真实生活场景中无效的“理论”模式。让我们走吧:
一些规范,为我们的情况增加透明度:
情景:
假设我们有一个服务接口:
public interface IProductService
{
// Just get the products from DB
IList<Products> GetAllProducts();
// Makes a conversion between product's current UM and requested 'toUnitMeasure'
double ConvertUnitMeasureTo(Product product, UnitMeasure toUnitMeasure);
}
现在让我们分析两种方法可能发生的事情:
GetAllProducts();
:
SqlException
。 ConvertUnitMeasureTo(Product product, UnitMeasure toUnitMeasure);
:
product
。toUnitMeasure
。product
当前的单位指标可能无法转换为toUnitMeasure
(例如:MASS到LENGTH)ArithmeticException
等。好到目前为止一切顺利。让我们来看看控制器:
[HttpPost]
public ActionResult Index(ProductViewModel model)
{
if(ModelState.IsValid)
{
// At this point, some of the (above enumerated) situations may occur.
// Some of them are Exceptions while another
// are unpleasant but 'expected' situations.
var result = _productService.ConvertToUnitMeasure(model.Product, model.UnitMeasure);
}
}
问题:
如何处理Controller
内的所有情况?而:
CustomException.Message
内对消息进行硬编码,不适合我的情况)The toUnitMeasure might be not found either.
制作RedirectToAction("CreateUnitMeasure","UnitMeasure")
); Controller
'瘦身'。例如:通过将Controller
分隔为更小的服务方法,避免在ConvertUnitMeasureTo(..)
内部而不是服务层中实施转换方法。 (希望不需要解释) 您的回答对我有价值,所以请不要犹豫,表达自己。非常感谢您的关注。