Sometimeswhen you are writing C# you get a lot of code that looks like this:

        public int SaveDraft(DocumentDraftDto dto)
        {
            try
            {
                int id = task.SaveDraft(dto);
                context.StatusCode = HttpStatusCode.Created;
                return id;
            }
            catch (Exception e)
            {
                log.Error(string.Format("An error occurred when saving the draft for Username={0}.", dto.UpdateUser), e);
                context.StatusCode = HttpStatusCode.InternalServerError;
                return 0;
            }
        }

        public List<DocumentDraftDto> GetDrafts(string userId)
        {
            try
            {
                List<DocumentDraftDto> documentDraftDtos = task.GetDrafts(userId);
                context.StatusCode = HttpStatusCode.OK;
                return documentDraftDtos;
            }
            catch (Exception e)
            {
                log.Error(string.Format("An error occurred when retrieving drafts for UserId={0}.", userId), e);
                context.StatusCode = HttpStatusCode.InternalServerError;
                return null;
            }
        }

The same try/catch with the same code repeated again and again.

One way to clean this up is create on generic try catch statement, and pass a function of the method you want invoked to it:

        public int SaveDraft(DocumentDraftDto dto)
        {
            return CallDocumentDraftTask(x => x.SaveDraft(dto));
        }

        public List<DocumentDraftDto> GetDrafts(string userId)
        {
            return CallDocumentDraftTask(x => x.GetDrafts(userId));
        }

        private T CallDocumentDraftTask<T>(Func<IDocumentDraftTask, T> func)
        {
            try
            {
                T resurlt = func(task);
                context.StatusCode = func.Method.Name.Contains("SaveDraft") ? HttpStatusCode.Created : HttpStatusCode.OK;
                return resurlt;
            }
            catch (Exception e)
            {
                log.Error(string.Format("An error occurred when " + func.Method.Name), e);
                context.StatusCode = HttpStatusCode.InternalServerError;
                return default(T);
            }
        }

There. Much cleaner. And less noise. And less code to maintain.

Thanks to Allan Wu for showing me this.