'Returning HandlerResponse from ExtensionMethod
I'm refactoring my commandhandlers to return responses through extension methods (or possible delegates). Trying to move from:
var object = _repo.GetObjectById(id);
if (object == null) return new Response();
to:
object.ReturnIfNull();
by using:
public static Response ReturnIfNull<T>(this T root)
{
if (root == null)
{
return new Response()
{
Errors = new List<ResponseError>
{
new()
{
ErrorCode = ErrorCode.Unknown.ToString(),
Field = $"{typeof(T)}Id"
}
}
};
}
return null;
}
Ofcourse this method atm return null or a Response to the handler. In that case, I should catch the result in the handler, and do another null-check before passing Response back to controller. My goals is to do this in a one-liner. Is this possible? So when ReturnIfNull() finds root to be null, the handlers returns the results from ReturnIfNull() straight to the object calling the handler. If ReturnIfNull() passes the null-check, the flow should continue in the handler..
I'm unexperienced with Delegates & Actions, can they play some role in fixing this? Or is it not possible at all?
Thanks in advance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
