Skip to main content
1 of 2

Better way to make a generic function that accepts both Actions and Func's as parameters

I've created a generic try catch I can apply throughout my code so I'm not repeating myself.

    private HttpResponseMessage TryCatch(Action action)
    {
        return TryCatch(() => { action(); return "ActionToFunc"; });
    }

    private HttpResponseMessage TryCatch<T>(Func<T> func)
    {
        try
        {
            var result = func();

            if (result.ToString() == "ActionToFunc")
            {
                return Request.CreateResponse(HttpStatusCode.OK);
            }

            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
        catch (ArgumentNullException)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError);
        }
    }

I can call it using:

TryCatch(() => myFunction(parameter));

Is there a better way of doing achieving the same result?