In my code I have many functions with this signature (params + return type), and they all use this same try-catch
clause.
public ActionResult methodName(int id)
{
try
{
//Some specific code here
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
}
Now, This is replicated over and over again, and I know that replication is bad.
The reason this happens, is because I want the code to be able to return multiple HttpStatusCodeResult
but I don't know a better way of doing it.
In this example, I return an internal server error and an OK answer. But what if I want to return another type of error ?
public ActionResult methodName(int id)
{
try
{
//Some specific code here
if(conditionA)
return return new HttpStatusCodeResult(HttpStatusCode.NotFound, "No Hamsters found!")
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
}
Is there a modular way of having behavior, without replication, inside my code? Is there a design or architectural pattern I can use? If so, which one?
You can factorize a little like this :
public static class Helper
{
public static ActionResult TryCatch(Func<ActionResult> funk)
{
try
{
if (funk != null)
{
ActionResult result = funk();
if (result != null)
return result;
}
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
And call it like this :
public ActionResult methodName(int id)
{
return Helper.TryCatch(() =>
{
//Some specific code here
if(conditionA)
return return new HttpStatusCodeResult(HttpStatusCode.NotFound, "No Hamsters found!")
return null;
};
}