In all the asp.net apis I have written I have adopted the global exception handler approach to returning errors.
It gives me a central location for logging and an easy way for nested services to fail fast.
Do you find all the if (result.errored) checks everywhere add a lot more conditional paths to your code?
Where are the sharp edges, in your experience, with this approach?
How do you feel about using an app framework type (ActionResult) throughout your business logic? Do all your libs take a dependency on Asp.net now?
Thanks for the interesting post.
If you do a good job of applying the single responsibility principle, in my experience the controller doesn’t usually have more than a handful of calls to make.
The if (action.Errored) are used more like guard clauses with early exits so it doesn’t feel to me like it gets too busy, could just be a preference though.
The biggest problem is constructors. I would love for new T() to return a Result with a bad request error if the validation failed. I end up moving this logic into a TFactory and then I’m left with anemic data models which doesn’t make my inner programmer happy... an object should be able to enforce it’s own rules about data validity and not offload that to some other class. I’m playing with a few solutions, but my favorite one won’t have the necessary language features (interfaces and abstract classes that can define static methods) until C# 8.0 (or even later :( )
ActionResult is used as the error type because it’s so handy in ASP.NET Core, i’ve Used other failure types, and sometimes my own depending on the context I’m working in.
If I need to keep web client framework code out of my domain layer, I’d probably have my domain code throw appropriate exceptions, and then apply a facade in me .net Core App that catches those exceptions and maps them to ActionResults. My main goal here is to avoid catching and handling exceptions in my controllers. Some other web framework might have a really elegant way of handling exceptions, and while I dislike it, it is a pattern than a lot of other developers understand.
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.