I prefer returning a 200 and handling the error at the application level
If I do not need to return any value
{
"status": "ok"
}
If I need to return a value
{
"status": "ok",
"result": [
{
"Name": "Fabio"
},
{
"Name": "Laura"
}
]
}
And in case an error occurs
{
"status": "ko",
"exceptionMessage": "Something went wrong!"
}
Consider including the following methods in the base class of your controllers
/// <summary>
/// Processes the request using a method that does not return any value
/// </summary>
/// <param name="action">The method to be used to process the request</param>
protected JsonResult ProcessRequest(Action action)
{
return ProcessRequest(() =>
{
action();
return null;
});
}
/// <summary>
/// Processes the request using a method that returns a value
/// </summary>
/// <param name="func">The method to be used to process the request</param>
protected JsonResult ProcessRequest(Func<object> func)
{
JsonResult jsonResult = new JsonResult();
try
{
object result = func();
if (result != null)
{
jsonResult.Data = new { status = "ok", result = result, };
}
else
{
jsonResult.Data = new { status = "ok", };
}
}
catch (Exception e)
{
string message = e.Message;
jsonResult.Data = new { status = "ko", exceptionMessage = message, };
}
return jsonResult;
}
Then your action methods would look like the following
public ActionResult DoThat()
{
return ProcessRequest(() =>
{
// Do something
});
}
public ActionResult ReturnPersonList()
{
return ProcessRequest(() =>
{
return new List<Person> { new Person { Name = "Fabio" }, new Person { Name = "Laura" } };
});
}