Return error message vs throw exception

asp.net-mvc, c#, error-handling

Solution

I wonder if it is good practice or not.

No, throwing exceptions to handle non-exceptional flow is bad design. Throwing exceptions comes at a cost and you should avoid them if you can handle your case with a normal flow.

Problem

I am writing a class library for a asp.net mvc project. Class library will return the entities and executes the basic functions. In the previous project I used a logic like that: ``` public class MyClassLibrary { public Response<ResponseMessage, MyEntity> GetMyEntity() { //Some code } public ResponseMessage SaveMyEntity(MyEntity e) { //Some code } } public class BaseController:Controller { public ActionResult JsonDataSourceRequest<T>(Func<Response<ResponseMessage, List<T>>> operation, [DataSourceRequest] DataSourceRequest request) { try { Response<ResponseMessage, List<T>> ret = operation(); if (ret.message.type == ReturnType.OK) { return Json(ret.result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); } else return ConvertToJson(ret.message); } catch (Exception ex) { ResponseMessage m = new ResponseMessage(); m.type = ReturnType.ERROR; m.text = ex.text; return ConvertToJson(m); } } public ActionResult PartialView<T>(Func<Response<ResponseMessage, T>> operation) { //Some code } public ActionResult Action(Func<ResponseMessage> operation) { //some code } } [CustomAuthorize] public class MyController : BaseController { public ActionResult MyEntityRead([DataSourceRequest] DataSourceRequest request) { return base.JsonDataSourceRequest(() => { return MyEntityService.GetAll(); }, request); } } ``` Here in order to use the BaseController's functions I always return Response or ResponseMessage Now I think that I could have custom exception classes and instead of returning a ResponseMessage from all the methods I could throw these exceptions. I wonder if it is a good practice or not. Thanks in advance.

Original source