PsdUtilities.QuickTryCatch
1.0.1
dotnet add package PsdUtilities.QuickTryCatch --version 1.0.1
NuGet\Install-Package PsdUtilities.QuickTryCatch -Version 1.0.1
<PackageReference Include="PsdUtilities.QuickTryCatch" Version="1.0.1" />
<PackageVersion Include="PsdUtilities.QuickTryCatch" Version="1.0.1" />
<PackageReference Include="PsdUtilities.QuickTryCatch" />
paket add PsdUtilities.QuickTryCatch --version 1.0.1
#r "nuget: PsdUtilities.QuickTryCatch, 1.0.1"
#:package PsdUtilities.QuickTryCatch@1.0.1
#addin nuget:?package=PsdUtilities.QuickTryCatch&version=1.0.1
#tool nuget:?package=PsdUtilities.QuickTryCatch&version=1.0.1
PsdUtilities.QuickTryCatch
A small, single-class utility library for a quick execution of tasks that require a try-catch block. Made with convenient and simple handle of any exception.
Features
- Sync/Async operation execution.
- Handle of all or specific exceptions using a convenient builder method (e.g.
.Catch<MyException>(ex => ...)
or.CatchAll(ex => ...)
). - Conditional exception handle (e.g.
CatchWhen<MyException>(ex => ex.StatusCode == 400, ex => ...)
. Same thing applies for.CatchAllWhen()
for catching every exception), async versions of these methods are also available. - Disregard of particular exceptions (e.g.
.Ignore<IOException>()
). - Unhandled exception behavior - either ignore them (i.e.
.IgnoreUnhandled()
default behavior), or rethrow them (i.e..RethrowUnhandled()
, keeps the stack trace). - Task execution repeat attempt in a case of a failure (i.e.
.WithRetries(retries: int, delay: TimeSpan)
), though delay is unrecommended for synchonous tasks, as it could block the main thread. Prefer just.WithRetries(retries: int)
. - Continuation with the result, including async overload, if the tasks succeeds, i.e.
.ContinueWith(result => ...)
, where the result is a generic parameter. If you dont want any result, but a plain void execution, its going to beobject?
by default, you can just discard it this like that:.ContinueWith(_ => <some actions unrelated to the result value>... )
. - Independent execution result that contains a
nullable result value
,bool Success
,nullable exception
andamount of retries for that execution to succeed
.
How to use
An example of referencing a method:
void FailableMethod()
{
// code that might throw an exception
}
TryCatch
.Execute(FailableMethod)
.Finalize(); // required in order to "build" according to the builder specifications and run the action task.
In this example, the FailableMethod
try to execute, if it fails, no exceptions will be thrown, the code will continue its work;<br>
You could also use a lambda expression for a short action.
TryCatch
.Execute(() => { Console.WriteLine("Hiii!!"); })
.Finalize();
<br>
When it comes to async methods, it must be Task or Task<T>, async void
won't be suitable.
Task AsyncFailableMethod()
{
throw new NotImplementedException(); // lets actually throw an exception
}
await TryCatch
.ExecuteAsync(AsyncFailableMethod)
.Catch<NotImplementedException>(ex => Console.WriteLine("This method is not implemented."))
.FinalizeAsync();
<br>
Now lets do something a little more complex!
async Task<string> ReadFileAsync()
{
var file = "myFile.txt";
var text = await File.ReadAllTextAsync(file);
return text;
}
var result = await TryCatch
.ExecuteAsync(ReadFileAsync!)
.WithRetries(retries: 5, delay: TimeSpan.FromSeconds(1))
.RethrowUnhandled()
.Ignore<OperationCanceledException>()
.Catch<IOException>(ex => Console.WriteLine("IO exception occured while trying to read the file: " + ex.Message))
.ContinueWith(text => Console.WriteLine($"File text:\n" + text), new ContinueOptions() { ExecutionOrder = ExecutionOrder.First })
.ContinueWith(text => Console.WriteLine("Successfully read the file!"), new ContinueOptions() { ExecutionOrder = ExecutionOrder.Last })
.FinalizeAsync();
if (result.IsSuccess)
{
// do something with the result
}
As a first step, it tries to execute the ReadFileAsync
, if it fails - it verifies the exception type. If the type is ignored - moves on, if its IOException
, it handles it, anything else - rethrows it outside the TryCatch
utility. You will need a global handler to catch it, or a try/catch body around it (but doesnt it defeat the entire purpose of the utility?!). Anyways, elsewise it moves on to the next attempt, prematurely waiting for exactly 1 second as we asked it to.
Finally, when it succeeds, according to our continuation options
, we can understand the execution order of the .ContinueWith
functions. Firstly display the file text, then the "success" message. If you dont provide the ExecutionOrder
, it will be set to sequential
, which by the way you cannot set manually, because the sequence is calculated using Factory
that keeps track of the state of the orders, but you can set your own order, using ExecutionOrder.FromValue()
, where you provide the order, which is ascending, lower values - gets executed first.
ExecutionOrder.First
and ExecutionOrder.Last
are nothing more than just ExecutionOrder.FromValue(int.MinValue)
and ExecutionOrder.FromValue(int.MaxValue)
.
Future features
- An oppurtunity to add a
CancellationToken
for the async methods, i somehow COMPLETELY forgot about their existence while writing the library - Conditional continuation maybe ?
Bug report
If you happen to find any bug which is not unlikely to occur, please post a new issue and i will fix it as soon as possible. My tests are far from perfect, they cover the essential usage of the library, but i doubt they clear out rare edge cases, so be cautios if you plan on using it.
Info
Library has been written in 1 whole day :]
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
.NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
.NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.