79327065

Date: 2025-01-03 16:39:58
Score: 2
Natty:
Report link

A lot depends on your project and what you're trying to achieve. Throwing exceptions for flow control works fine and .NET 9 has gained significant performance improvements. However, exceptions should only be used for exceptional cases. I won't dive into details as you can find many resources online. As a rule of thumb, remember that service methods and external dependencies outside of your controllers shouldn't know anything about HTTP status codes.

Say you have a service method that accepts an ID and returns an object. If the ID is not found, you want to return a NotFound result. You can throw an exception and handle it down the pipeline but consider the drawbacks. First, you're losing performance albeit negligible. Secondly, your flow control is not clear and consequently, documentation, maintenance, and following the code becomes harder. Thirdly and perhaps more importantly, it affects how you write your tests.

Integration tests are always better since you want routing, filters, model binding, authorization, etc. to apply. But unit tests have their place and I think you should do both. Back to our example, if you throw an exception to signify that a resource doesn't exist, your unit tests won't pick that up. How do you write a unit test for testing your controller behavior to identify that a nonexistent ID should return a NotFound result? That's why it's better to use the result object pattern.

In your service method, you do what needs to be done (validation, data access, etc.) and return a result object. In your controller, you map that to appropriate HTTP responses. That gives you better performance, clear intentions, and better maintenance, and you can more easily write tests and document your API.

It's always better to keep your controllers thin, and most applications delegate the work to another handler (i.e. using MediatR). Whether you use the result object pattern or throw exceptions for flow control, you want to ask yourself what is it you're trying to test. And in the context of an API, the answer is the whole pipeline. You want filters, model binding and validation, authorization, and everything else in place, which is why integration tests give you more bang for your buck and make life easier.

More to read:

Reasons:
  • Blacklisted phrase (1): How do you
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: in3xu4