Search code examples
c#filterasp.net-coreactionresult

Is it good idea to have a general try/catch in every method in a controller or is there a better way?


I'm trying to improve my MVC.NET Core-fu and I ended up in a bunch of methods in all my controllers looking like this (note the outermost, general, repetitive try-catch).

[HttpPost]
public IActionResult DoSomething([FromBody] Thing thing)
{
  try
  {
    if (...)
      return Ok(thing);
    else
      return NotFound();
  }
  catch (Exception) { return BadRequest(); }
}

The way I see, I want to have the baddy-requesty just in case. Now, that adds a lot of code to otherwise rather simple controller and I have a suspicion that someone before has thought of this and proposed a solution.

I haven't found such thing (and I was informed that filters are obsolete for usage in Core). Possibly it's because I'm not familiar with the right search keys.


Solution

  • This seems excessive to me. Many methods won't execute instructions that are likely to fail. For those extremely rare cases, a global error handler would be more than sufficient.

    For those methods that access the disk, a database, or perform calculations that could raise exceptions (something you should probably be avoiding in the first place), a try...catch block makes sense.

    But even in these cases, if a method with a try...catch handler calls another method, there is no reason to put handlers in that other method.