1

Almost all my codes in C# are something like this:

try
{
   response = SomeMethod(requestModel);
}
catch (Exception ex)
{
  this.logger.Log(ex.MoreDetails());
  response = this.BadRequest();
}

the SomeMethod is the only thing that is different, but all the request models inherit some parent model. Any tips so I don't have to keep repeating this on all my codes? The response also use the same generic model.

MilkTea027
  • 301
  • 1
  • 5
  • 24
  • Just have a look at this answer, you should define a base class for that and implement that function. or just a static method with a delegate. https://stackoverflow.com/a/2139878/13583842 – TinoZ Jun 08 '20 at 12:00
  • You could write a helper method that takes a `Func` and do the try catch and logging for you. – juharr Jun 08 '20 at 12:00
  • 1
    If that is really all there is to all your code then just handle exceptions inside `SomeMethod` and return `BadRequest` if necessary. – Crowcoder Jun 08 '20 at 12:04

1 Answers1

3

You can create a method which accepts Func as parameter:

class Request{} 
class BadRequest:Request{}
class AnotherRequest:Request{}

static Request HandleException(Func<Request> f)
{
    Request result ;
    try
    {
        result = f();
    }
    catch (Exception ex)
    {
        result = new BadRequest();
    }
    return result;
}

static AnotherRequest SomeMethod(int i) => new AnotherRequest();  

And usage:

Request result = HandleException(() => SomeMethod(1));
Guru Stron
  • 102,774
  • 10
  • 95
  • 132