|
1 | 1 | # OperationResult |
2 | | -A reusable class for capturing multiple errors and success tracking when performing all kinds of code operations. |
| 2 | +A reusable class for capturing multiple errors and success tracking when performing all kinds of code operations. OperationResult lets you return a valid object instead of throwing and capturing exceptions. |
| 3 | +The OperationResult class will also automatically log entries if an instance of ILogger has been passed during construction. |
| 4 | + |
| 5 | +Example: |
| 6 | +```cs |
| 7 | +public OperationResult CustomLogicMethod() |
| 8 | +{ |
| 9 | + var operationResult = new OperationResult(); |
| 10 | + |
| 11 | + // Do custom logic work |
| 12 | +
|
| 13 | + operationResult.AppendError("The custom logic did not work"); |
| 14 | + operationResult.AppendException(new Exception("The custom logic method threw and exception.")); |
| 15 | + |
| 16 | + return operationResult; |
| 17 | +} |
| 18 | + |
| 19 | +var customLogicResult = CustomLogicMethod(); |
| 20 | +// customLogicResult.Success is false |
| 21 | +// customLogicResult.Errors contains two errors, one with the set message and the other with the set exception. |
| 22 | +``` |
| 23 | + |
| 24 | +## Returning data and objects |
| 25 | +You can instantiate an OperationResult object by specifying a return type as a generic: |
| 26 | + |
| 27 | +```cs |
| 28 | +public OperationResult<MemoryStream> GetStream() |
| 29 | +{ |
| 30 | + var operationResult = new OperationResult<MemoryStream>(); |
| 31 | + operationResult.ResultObject = [stream reference]; |
| 32 | + return operationResult; |
| 33 | +} |
| 34 | + |
| 35 | +var getStreamResult = GetStream(); |
| 36 | +// getStreamResult.ResultObject contains a reference of the resulting object of MemoryStream type; |
| 37 | +``` |
| 38 | + |
| 39 | +## Passing an instance of ILogger. |
| 40 | +OperationResult will log to a passed ILogger if it is passed during construction. |
| 41 | +Every method provides a log-level override. |
| 42 | +```cs |
| 43 | +public OperationResult CustomLogicMethod(ILogger logger) |
| 44 | +{ |
| 45 | + var operationResult = new OperationResult(logger); |
| 46 | + |
| 47 | + // Do custom logic work |
| 48 | +
|
| 49 | + operationResult.AppendError("The custom logic did not work"); // this call will be logged to the logger with severity Error. |
| 50 | + operationResult.AppendException(new Exception("The custom logic method threw and exception.")); // this call will be logged to the logger with severity Error. |
| 51 | +
|
| 52 | + return operationResult; |
| 53 | +} |
| 54 | +``` |
0 commit comments