I'd like to know what are the best practices, or the best / elegant way to bring up error message from Data Access Layer (or other layers) to the View.
I'm using ASP.NET MVC 5, my project has multiple layers, such as:
I have two types of "error messages" that I'd like to bring up to the IHM:
Errors generated by Exceptions: exception is logged and a human friendly error message is displayed.
Business errors: for example, an action needs a customer has at least 3 invoices and he only has 2.
In another project, here is what I did:
Controller
[HttpPost]
public ActionResult Edit()
{
//...
ErrorModel errorModel = new ErrorModel();
BusinessLayer businessLayer = new businessLayer()
businessLayer.Edit( /* some parameters */, out errorModel)
TempData[Error] = errorModel
}
View
@{
var errorModel = TempData[Error]
}
/* if error model is not null, display the error correctly */
In every layer, all my methods have a out ErrorModel
variable which is filled in try / catch
blocks, or because of business failure and I definitely don't like that.
I found a lot of answers on Google or Stack Overflow, but all focuses on how to catch errors.
*My question goes further: Once catched, how to bring errors up from the layer it occurs to the view on an elegant way?
The general approach of that is throwing exceptions in all layers and handle them in the top layer (presentation - controller actions). Exception is one type of method result and you don't need to specify it in method signature. The approach of passing out errorModel is not good because every method should return it and every method should have try catch block.
In business layer you can have some business exceptions which are derived from Exception class and have some additional information. Or you can use general ApplicationException class.
So, your controller can look like
[HttpPost]
public ActionResult Edit()
{
try
{
businessLayer.Edit( /* some parameters */)
return Ok();
}
catch(BadAcctionException)
{
TempData[Error] = "Bad business operation";
return BadBusinessAction();
}
catch(ApplicationException ex)
{
TempData[Error] = ex.Message;
return Fail();
}
}
and inside businessLayer.Edit you throw an exception if something wrong is.