// Copyright (c) The Geekeey Authors // SPDX-License-Identifier: EUPL-1.2 using System.Diagnostics.Contracts; namespace Geekeey.Extensions.Result; /// /// A class containing various utility methods, a 'prelude' to the rest of the library. /// /// /// This class is meant to be imported statically, e.g. using static Geekeey.Extensions.Result.Prelude;. /// Recommended to be imported globally via a global using statement. /// public static class Prelude { /// /// Creates a result containing an success value. /// /// The type of the success value. /// The success value to create the result from. [Pure] public static Result Success(T value) => new(value); /// /// Creates a result containing a failure value. /// /// The type of an success value in the result. /// The failure value to create the result from. [Pure] public static Result Failure(Error error) => new(error); /// /// Tries to execute a function and return the result. If the function throws an exception, the exception will be /// returned wrapped in an . /// /// The type the function returns. /// The function to try execute. /// A result containing the return value of the function or an containing the /// exception thrown by the function. [Pure] public static Result Try(Func function) { try { return new Result(function()); } catch (Exception exception) { return new Result(new ExceptionError(exception)); } } /// /// Tries to execute an asynchronous function and return the result. If the function throws an exception, the /// exception will be returned wrapped in an . /// /// The type the function returns. /// The function to try execute. /// A result containing the return value of the function or an containing the /// exception thrown by the function. [Pure] public static async ValueTask> TryAsync(Func> function) { try { return new Result(await function()); } catch (Exception exception) { return new Result(new ExceptionError(exception)); } } /// /// Tries to execute an asynchronous function and return the result. If the function throws an exception, the /// exception will be returned wrapped in an . /// /// The type the function returns. /// The function to try execute. /// A result containing the return value of the function or an containing the /// exception thrown by the function. [Pure] public static async Task> TryAsync(Func> function) { try { return new Result(await function()); } catch (Exception exception) { return new Result(new ExceptionError(exception)); } } }