├── .gitignore ├── LICENSE ├── README.md ├── ResultType.sln ├── src └── ResultType │ ├── Extensions │ └── ResultExtensions.cs │ ├── Result.cs │ └── ResultType.csproj └── test └── ResultType.Tests ├── GlobalUsings.cs ├── ResultTests.cs ├── ResultType.Tests.csproj ├── StackTraceTests.cs └── UseCases.cs /.gitignore: -------------------------------------------------------------------------------- 1 | # User-specific files 2 | *.rsuser 3 | *.suo 4 | *.user 5 | *.userosscache 6 | *.sln.docstates 7 | 8 | # User-specific files (MonoDevelop/Xamarin Studio) 9 | *.userprefs 10 | 11 | # Mono auto generated files 12 | mono_crash.* 13 | 14 | # Build results 15 | [Dd]ebug/ 16 | [Dd]ebugPublic/ 17 | [Rr]elease/ 18 | [Rr]eleases/ 19 | x64/ 20 | x86/ 21 | [Aa][Rr][Mm]/ 22 | [Aa][Rr][Mm]64/ 23 | bld/ 24 | [Bb]in/ 25 | [Oo]bj/ 26 | [Ll]og/ 27 | [Ll]ogs/ 28 | 29 | # Visual Studio 2015/2017 cache/options directory 30 | .vs/ 31 | # Uncomment if you have tasks that create the project's static files in wwwroot 32 | #wwwroot/ 33 | 34 | # Visual Studio 2017 auto generated files 35 | Generated\ Files/ 36 | 37 | # MSTest test Results 38 | [Tt]est[Rr]esult*/ 39 | [Bb]uild[Ll]og.* 40 | 41 | # NUnit 42 | *.VisualState.xml 43 | TestResult.xml 44 | nunit-*.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # NuGet Symbol Packages 183 | *.snupkg 184 | # The packages folder can be ignored because of Package Restore 185 | **/[Pp]ackages/* 186 | # except build/, which is used as an MSBuild target. 187 | !**/[Pp]ackages/build/ 188 | # Uncomment if necessary however generally it will be regenerated when needed 189 | #!**/[Pp]ackages/repositories.config 190 | # NuGet v3's project.json files produces more ignorable files 191 | *.nuget.props 192 | *.nuget.targets 193 | 194 | # Microsoft Azure Build Output 195 | csx/ 196 | *.build.csdef 197 | 198 | # Microsoft Azure Emulator 199 | ecf/ 200 | rcf/ 201 | 202 | # Windows Store app package directories and files 203 | AppPackages/ 204 | BundleArtifacts/ 205 | Package.StoreAssociation.xml 206 | _pkginfo.txt 207 | *.appx 208 | *.appxbundle 209 | *.appxupload 210 | 211 | # Visual Studio cache files 212 | # files ending in .cache can be ignored 213 | *.[Cc]ache 214 | # but keep track of directories ending in .cache 215 | !?*.[Cc]ache/ 216 | 217 | # Others 218 | ClientBin/ 219 | ~$* 220 | *~ 221 | *.dbmdl 222 | *.dbproj.schemaview 223 | *.jfm 224 | *.pfx 225 | *.publishsettings 226 | orleans.codegen.cs 227 | 228 | # Including strong name files can present a security risk 229 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 230 | #*.snk 231 | 232 | # Since there are multiple workflows, uncomment next line to ignore bower_components 233 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 234 | #bower_components/ 235 | 236 | # RIA/Silverlight projects 237 | Generated_Code/ 238 | 239 | # Backup & report files from converting an old project file 240 | # to a newer Visual Studio version. Backup files are not needed, 241 | # because we have git ;-) 242 | _UpgradeReport_Files/ 243 | Backup*/ 244 | UpgradeLog*.XML 245 | UpgradeLog*.htm 246 | ServiceFabricBackup/ 247 | *.rptproj.bak 248 | 249 | # SQL Server files 250 | *.mdf 251 | *.ldf 252 | *.ndf 253 | 254 | # Business Intelligence projects 255 | *.rdl.data 256 | *.bim.layout 257 | *.bim_*.settings 258 | *.rptproj.rsuser 259 | *- [Bb]ackup.rdl 260 | *- [Bb]ackup ([0-9]).rdl 261 | *- [Bb]ackup ([0-9][0-9]).rdl 262 | 263 | # Microsoft Fakes 264 | FakesAssemblies/ 265 | 266 | # GhostDoc plugin setting file 267 | *.GhostDoc.xml 268 | 269 | # Node.js Tools for Visual Studio 270 | .ntvs_analysis.dat 271 | node_modules/ 272 | 273 | # Visual Studio 6 build log 274 | *.plg 275 | 276 | # Visual Studio 6 workspace options file 277 | *.opt 278 | 279 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 280 | *.vbw 281 | 282 | # Visual Studio LightSwitch build output 283 | **/*.HTMLClient/GeneratedArtifacts 284 | **/*.DesktopClient/GeneratedArtifacts 285 | **/*.DesktopClient/ModelManifest.xml 286 | **/*.Server/GeneratedArtifacts 287 | **/*.Server/ModelManifest.xml 288 | _Pvt_Extensions 289 | 290 | # Paket dependency manager 291 | .paket/paket.exe 292 | paket-files/ 293 | 294 | # FAKE - F# Make 295 | .fake/ 296 | 297 | # CodeRush personal settings 298 | .cr/personal 299 | 300 | # Python Tools for Visual Studio (PTVS) 301 | __pycache__/ 302 | *.pyc 303 | 304 | # Cake - Uncomment if you are using it 305 | # tools/** 306 | # !tools/packages.config 307 | 308 | # Tabs Studio 309 | *.tss 310 | 311 | # Telerik's JustMock configuration file 312 | *.jmconfig 313 | 314 | # BizTalk build output 315 | *.btp.cs 316 | *.btm.cs 317 | *.odx.cs 318 | *.xsd.cs 319 | 320 | # OpenCover UI analysis results 321 | OpenCover/ 322 | 323 | # Azure Stream Analytics local run output 324 | ASALocalRun/ 325 | 326 | # MSBuild Binary and Structured Log 327 | *.binlog 328 | 329 | # NVidia Nsight GPU debugger configuration file 330 | *.nvuser 331 | 332 | # MFractors (Xamarin productivity tool) working folder 333 | .mfractor/ 334 | 335 | # Local History for Visual Studio 336 | .localhistory/ 337 | 338 | # BeatPulse healthcheck temp database 339 | healthchecksdb 340 | 341 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 342 | MigrationBackup/ 343 | 344 | # Ionide (cross platform F# VS Code tools) working folder 345 | .ionide/ 346 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Tobias Streng 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ResultType 2 | A Proposal of a Result Type in .NET 3 | 4 | ## When to use 5 | 6 | This Result Type is useful in scenarios, where you want to mildly enforce checking, if the underlying method has executed successfully. 7 | Additionally you will get a cleaner error-handling and reduce the risk of NullReferenceExceptions. 8 | 9 | ## Usage 10 | 11 | ### 1. Copy the class definitions from `Result.cs` and `ResultExtensions.cs` to your code base and make them accessible publicly. 12 | 13 | ### 2. Use `Result` or `Result` as return value for all relevant functions: 14 | 15 | ``` 16 | private Result GetPersonFromDatabase(Guid id) 17 | { 18 | try 19 | { 20 | return database.GetPersonById(id); 21 | } 22 | catch (Exception ex) 23 | { 24 | return ex; 25 | } 26 | } 27 | ``` 28 | 29 | As you can see, the Result Type also has implicit casts implemented, that will reduce the amount of code needed. 30 | 31 | ### 3. Use the `.Check()` Extension Method to quickly check and throw. 32 | ### 4. Return any thrown exceptions from `.Check()` without worries about the StackTrace, as it gets preserved. 33 | 34 | ## Features 35 | 36 | - Implicit castings allow you to directly return the desired type, which will be casted either to a positive `Result`, when you return an object of type ``, or to a negative `Result` / `Result`, when you return an `Exception` object. 37 | - The Extension Method `Check()` quickly allows you to check if a `Result` was successfull and throw the underlying exception (**while preserving the StackTrace**) if it was not. 38 | 39 | ``` 40 | try 41 | { 42 | Result result = GetResult().Check(); 43 | } 44 | catch (Exception ex) 45 | { 46 | //Here the Exception includes the StackTrace of all underlying (rethrowing) Methods 47 | //See StackTraceTest for examples 48 | logger.LogError(ex.ToString()); 49 | } 50 | 51 | ``` 52 | - `Result` is inheriting `Result`, so you can always cast to a normal `Result` if you don't need the payload `` anymore. -------------------------------------------------------------------------------- /ResultType.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30114.105 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D48D0294-50FE-4CC3-B294-532E4DD77617}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResultType", "src\ResultType\ResultType.csproj", "{C8BAC03E-FF41-477F-A12E-EC243B3AFA18}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{961FBD97-BC5D-4F87-956B-440C9309A3B2}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResultType.Tests", "test\ResultType.Tests\ResultType.Tests.csproj", "{39EA7006-91F9-44EA-AB07-E44E055BA36B}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {C8BAC03E-FF41-477F-A12E-EC243B3AFA18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {C8BAC03E-FF41-477F-A12E-EC243B3AFA18}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {C8BAC03E-FF41-477F-A12E-EC243B3AFA18}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {C8BAC03E-FF41-477F-A12E-EC243B3AFA18}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {39EA7006-91F9-44EA-AB07-E44E055BA36B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {39EA7006-91F9-44EA-AB07-E44E055BA36B}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {39EA7006-91F9-44EA-AB07-E44E055BA36B}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {39EA7006-91F9-44EA-AB07-E44E055BA36B}.Release|Any CPU.Build.0 = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(NestedProjects) = preSolution 33 | {C8BAC03E-FF41-477F-A12E-EC243B3AFA18} = {D48D0294-50FE-4CC3-B294-532E4DD77617} 34 | {39EA7006-91F9-44EA-AB07-E44E055BA36B} = {961FBD97-BC5D-4F87-956B-440C9309A3B2} 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /src/ResultType/Extensions/ResultExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Tobias Streng, MIT license 2 | 3 | using System.Runtime.Serialization; 4 | 5 | namespace ResultType.Extensions; 6 | 7 | public static class ResultExtensions 8 | { 9 | /// 10 | /// Checks if the was not successful and throws the underlying exception, if available. 11 | /// While re-throwing, it preserves the StackTrace. Returns the Result if successful, so that it can be quickly checked. 12 | /// 13 | /// 14 | public static Result Check(this Result result) 15 | { 16 | if (!result.Success) 17 | { 18 | var error = result.GetError(); 19 | PreserveStackTrace(error); 20 | throw error; 21 | } 22 | return result; 23 | } 24 | 25 | /// 26 | /// Checks if the "/> was not successful and throws the underlying exception, if available. 27 | /// While re-throwing, it preserves the StackTrace. Returns the Result if successful, so that it can be quickly checked. 28 | /// 29 | /// 30 | public static Result Check(this Result result) where T : class 31 | { 32 | if (!result.Success) 33 | { 34 | var error = result.GetError(); 35 | PreserveStackTrace(error); 36 | throw error; 37 | } 38 | return result; 39 | } 40 | 41 | /// 42 | /// Preserves the StackTrace, so that the Exception can be catched and re-thrown over multiple layers. 43 | /// 44 | /// https://stackoverflow.com/a/2085377 45 | private static void PreserveStackTrace(Exception exception) 46 | { 47 | var streamingContext = new StreamingContext(StreamingContextStates.CrossAppDomain); 48 | var objectManager = new ObjectManager(null, streamingContext); 49 | var serializationInfo = new SerializationInfo(exception.GetType(), new FormatterConverter()); 50 | 51 | exception.GetObjectData(serializationInfo, streamingContext); 52 | objectManager.RegisterObject(exception, 1, serializationInfo); 53 | objectManager.DoFixups(); 54 | } 55 | } -------------------------------------------------------------------------------- /src/ResultType/Result.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Tobias Streng, MIT license 2 | 3 | namespace ResultType; 4 | 5 | /// 6 | /// Used to determine, whether a method executes successfully or not. Has implicit cast implemented: 7 | /// Return (or inherited type) to return a Result with Success set to 'false'. 8 | /// 9 | public class Result 10 | { 11 | protected readonly Exception? error; 12 | 13 | /// 14 | /// Indicates if the operation was successful. 15 | /// 16 | public bool Success { get; protected set; } 17 | 18 | /// 19 | /// Gets the message of the Exception, if available. 20 | /// 21 | public string Message { get => error?.Message ?? ""; } 22 | 23 | protected Result(bool success, Exception? error) 24 | { 25 | Success = success; 26 | this.error = error; 27 | } 28 | 29 | /// 30 | /// Gets the error payload of the failed result. 31 | /// 32 | /// 33 | public Exception GetError() => error 34 | ?? throw new InvalidOperationException($"Error property for this Result not set."); 35 | 36 | /// 37 | /// Returns a positive Result. 38 | /// 39 | public static Result Ok 40 | { 41 | get => new Result(true, null); 42 | } 43 | 44 | /// 45 | /// Returns a negative Result with an Exception as payload. 46 | /// 47 | public static Result Error(Exception error) 48 | { 49 | return new Result(false, error); 50 | } 51 | 52 | /// 53 | /// Implicit cast from type Exception (or inherited) to Result with Success set to 'false'. 54 | /// 55 | public static implicit operator Result(Exception exception) => 56 | new Result(false, exception); 57 | } 58 | 59 | /// 60 | /// Used to determine, whether a method executes successfully or not. Has implicit casts implemented: 61 | /// Return to return a successful Result with this payload. 62 | /// Return (or inherited type) to return a Result with Success set to 'false'. 63 | /// 64 | /// 65 | public sealed class Result : Result 66 | where TPayload : class 67 | { 68 | private readonly TPayload? payload; 69 | 70 | private Result(TPayload? payload, Exception? error, bool success) : base(success, error) 71 | { 72 | this.payload = payload; 73 | } 74 | 75 | public Result(TPayload payload) : base(true, null) 76 | { 77 | this.payload = payload ?? throw new ArgumentNullException(nameof(payload)); 78 | } 79 | 80 | public Result(Exception error) : base(false, error) 81 | { 82 | } 83 | 84 | /// 85 | /// Gets the underlying payload of the successful result. 86 | /// 87 | /// 88 | public TPayload GetOk() => Success 89 | ? payload ?? throw new InvalidOperationException($"Payload for Result<{typeof(TPayload)}> was not set.") 90 | : throw new InvalidOperationException($"Operation for Result<{typeof(TPayload)}> was not successful."); 91 | 92 | /// 93 | /// Gets the error payload of the failed result. 94 | /// 95 | /// 96 | public new Exception GetError() => error 97 | ?? throw new InvalidOperationException($"Error property for Result<{typeof(TPayload)}> not set."); 98 | 99 | /// 100 | /// Returns a positive Result with an object as payload. 101 | /// 102 | public new static Result Ok(TPayload payload) 103 | { 104 | return new Result(payload, null, true); 105 | } 106 | 107 | /// 108 | /// Returns a negative Result with an Exception as payload. 109 | /// 110 | public new static Result Error(Exception error) 111 | { 112 | return new Result(null, error, false); 113 | } 114 | 115 | /// 116 | /// Implicit cast from type to Result with Success set to 'true'. 117 | /// 118 | public static implicit operator Result(TPayload payload) => 119 | new(payload, null, true); 120 | 121 | /// 122 | /// Implicit cast from type Exception (or inherited) to Result with Success set to 'false'. 123 | /// 124 | public static implicit operator Result(Exception exception) => 125 | new(exception); 126 | } -------------------------------------------------------------------------------- /src/ResultType/ResultType.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /test/ResultType.Tests/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using NUnit.Framework; 2 | global using ResultType; 3 | global using ResultType.Extensions; -------------------------------------------------------------------------------- /test/ResultType.Tests/ResultTests.cs: -------------------------------------------------------------------------------- 1 | namespace ResultType.Tests; 2 | 3 | public class ResultTests 4 | { 5 | [Test] 6 | public void GetOkTest() 7 | { 8 | var okResult = Result.Ok; 9 | var okResult2 = Result.Ok("Test"); 10 | 11 | Assert.True(okResult.Success); 12 | Assert.True(okResult2.Success); 13 | } 14 | 15 | [Test] 16 | public void GetErrorTest() 17 | { 18 | var exception = new Exception("Test"); 19 | var errorResult = Result.Error(exception); 20 | var errorResult2 = Result.Error(exception); 21 | 22 | Assert.False(errorResult.Success); 23 | Assert.False(errorResult2.Success); 24 | } 25 | 26 | [Test] 27 | public void ImplicitCastTest() 28 | { 29 | var exception = new Exception("Test"); 30 | Result errorResult = exception; 31 | Result errorResult2 = exception; 32 | Result okResult2 = "Test"; 33 | 34 | Assert.False(errorResult.Success); 35 | Assert.False(errorResult2.Success); 36 | Assert.True(okResult2.Success); 37 | } 38 | 39 | [Test] 40 | public void ThrowTest() 41 | { 42 | var okResult = Result.Ok; 43 | var okResult2 = Result.Ok("Test"); 44 | 45 | var exception = new Exception("Test"); 46 | Result errorResult = exception; 47 | Result errorResult2 = exception; 48 | 49 | Assert.DoesNotThrow(() => okResult.Check()); 50 | Assert.DoesNotThrow(() => okResult2.Check()); 51 | 52 | Assert.Throws(exception.GetType(), () => errorResult.Check()); 53 | Assert.Throws(exception.GetType(), () => errorResult2.Check()); 54 | } 55 | } -------------------------------------------------------------------------------- /test/ResultType.Tests/ResultType.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /test/ResultType.Tests/StackTraceTests.cs: -------------------------------------------------------------------------------- 1 | namespace ResultType.Tests; 2 | 3 | public class StackTraceTests 4 | { 5 | [Test] 6 | public void StackTraceContainsThrowingMethodNameTest() 7 | { 8 | var result = Stack1(); 9 | 10 | var error = result.GetError(); 11 | 12 | Assert.That(error.StackTrace!.Contains(nameof(StackTraceTestInternal))); 13 | Assert.That(error is InvalidOperationException); 14 | } 15 | 16 | [Test] 17 | public void StackTraceContainsAllMethodNamesTest() 18 | { 19 | var result = RethrowStack1(); 20 | 21 | var error = result.GetError(); 22 | 23 | Assert.That(error.StackTrace!.Contains(nameof(StackTraceTestInternal))); 24 | Assert.That(error.StackTrace!.Contains(nameof(RethrowStack1))); 25 | Assert.That(error.StackTrace!.Contains(nameof(RethrowStack2))); 26 | Assert.That(error is InvalidOperationException); 27 | } 28 | 29 | private Result RethrowStack1() 30 | { 31 | try 32 | { 33 | var result = RethrowStack2(); 34 | result.Check(); 35 | return result; 36 | } 37 | catch (Exception ex) 38 | { 39 | return ex; 40 | } 41 | } 42 | 43 | private Result RethrowStack2() 44 | { 45 | try 46 | { 47 | var result = StackTraceTestInternal(); 48 | result.Check(); 49 | return result; 50 | } 51 | catch (Exception ex) 52 | { 53 | return ex; 54 | } 55 | } 56 | 57 | private Result Stack1() => Stack2(); 58 | 59 | private Result Stack2() => StackTraceTestInternal(); 60 | 61 | private Result StackTraceTestInternal() 62 | { 63 | try 64 | { 65 | throw new InvalidOperationException("Test"); 66 | } 67 | catch (Exception ex) 68 | { 69 | return ex; 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /test/ResultType.Tests/UseCases.cs: -------------------------------------------------------------------------------- 1 | namespace ResultType.Tests; 2 | 3 | public class UseCases 4 | { 5 | [Test] 6 | public void SampleUseCase() 7 | { 8 | var result = CopyPerson(); 9 | 10 | if (!result.Success) 11 | Console.WriteLine($"{nameof(CopyPerson)} was not successfull: {result.Message}"); 12 | } 13 | 14 | [Test] 15 | public void SampleFailingUseCase() 16 | { 17 | var result = CopyPersonThrowing(); 18 | 19 | if (!result.Success) 20 | Console.WriteLine($"{nameof(CopyPerson)} was not successfull: {result.Message}"); 21 | } 22 | 23 | private Result CopyPerson() 24 | { 25 | try 26 | { 27 | var personResult = GetPersonFromDatabase() 28 | .Check(); 29 | 30 | return InsertPersonToOtherDatabase(personResult.GetOk()) 31 | .Check(); 32 | } 33 | catch (Exception ex) 34 | { 35 | return ex; 36 | } 37 | } 38 | 39 | private Result CopyPersonThrowing() 40 | { 41 | try 42 | { 43 | var personResult = GetPersonFromDatabaseThrowing() 44 | .Check(); 45 | 46 | return InsertPersonToOtherDatabase(personResult.GetOk()) 47 | .Check(); 48 | } 49 | catch (Exception ex) 50 | { 51 | return ex; 52 | } 53 | } 54 | 55 | private Result GetPersonFromDatabase() 56 | { 57 | try 58 | { 59 | return new Person("Test", 20); 60 | } 61 | catch (Exception ex) 62 | { 63 | return ex; 64 | } 65 | } 66 | 67 | private Result GetPersonFromDatabaseThrowing() 68 | { 69 | try 70 | { 71 | throw new InvalidDataException("Person not available!"); 72 | } 73 | catch (Exception ex) 74 | { 75 | return ex; 76 | } 77 | } 78 | 79 | private Result InsertPersonToOtherDatabase(Person person) 80 | { 81 | try 82 | { 83 | return Result.Ok; 84 | } 85 | catch (Exception ex) 86 | { 87 | return ex; 88 | } 89 | } 90 | } 91 | 92 | internal record Person(string Name, int Age); --------------------------------------------------------------------------------