Reduce Boilerplate of WebAPI Controller

Viewed 30

I was helping a colleague to refactor some old code that has been written and it's still developed in those days... we've found a pattern that occurs in each ActionController we write. I was wondering if it's possible to have a weaver that avoids the boilerplate of repeating in each method.

Here's a simplification of the method, what happen in the [Action] is the operation that're proprietary of the method.

   public async Task<IActionResult> SomeActionController(SomeViewModel model)
   {
     if (model == null)
     {
       return await Task.FromResult(BadRequest());
     }

     try
     {
       if (!ModelState.IsValid)
       {
         return await Task.FromResult(BadRequest(ModelState));
       }

       var res = await _someService.DoSomething(model);
       if (res.IsSuccessStatusCode)
         return await Task.FromResult(Ok());
       else
       {
         _logger.LogError(res.ReasonPhrase);
         return await Task.FromResult(new 
            StatusCodeResult(StatusCodes.Status500InternalServerError));
       }
     }
     catch (Exception ex)
     {
       string errorMessage = $"SomeErrorDescription";
       _logger.LogError(errorMessage, ex);
       throw;
   }
}

I wish to have a Weaver that adds

     if (model == null)
     {
       return await Task.FromResult(BadRequest());
     }

     try
     {
       if (!ModelState.IsValid)
       {
         return await Task.FromResult(BadRequest(ModelState));
       }
        // [Original code]
     }
     catch(Exception ex)
     {
        string errorMessage = Calling method + Error;
       _logger.LogError(errorMessage, ex);
       throw;
     }
}


Is it possible with Fody?
0 Answers
Related