Class ExceptionHandler<TException>
- Namespace
- Cuemon
- Assembly
- Cuemon.Kernel.dll
Provides a generic way to handle an Exception.
public class ExceptionHandler<TException> where TException : Exception
Type Parameters
TExceptionThe type of the Exception.
- Inheritance
-
ExceptionHandler<TException>
Examples
The following example demonstrates how to use
using System;
using Cuemon; // for ExceptionCondition, ExceptionHandler, ExceptionInvoker
namespace MyApp.Examples;
public class ExceptionHandlerExample
{
public void Demonstrate()
{
// Build the chain: Condition -> Handler -> Invoker
ExceptionInvoker<ArgumentException> invoker = new ExceptionCondition<ArgumentException>()
.IsTrue(() => string.IsNullOrEmpty(Environment.GetEnvironmentVariable("API_KEY")))
.Create(() => new ArgumentException("API_KEY environment variable is not set."));
// When TryThrow is called, it evaluates the condition
// and throws the exception created by the handler if the condition matches
invoker.TryThrow();
// The handler can be stored and reused to create different invokers
ExceptionHandler<InvalidOperationException> handler =
new ExceptionCondition<InvalidOperationException>().IsTrue(() => true);
// Create different invokers from the same handler
var invokerA = handler.Create(() => new InvalidOperationException("Reason A"));
var invokerB = handler.Create(() => new InvalidOperationException("Reason B"));
// invokerA.TryThrow(); // throws "Reason A"
// invokerB.TryThrow(); // throws "Reason B"
}
}
Methods
Create(Func<TException>)
Specifies the function delegate that determines the Exception to be thrown.
public ExceptionInvoker<TException> Create(Func<TException> handler)
Parameters
Returns
- ExceptionInvoker<TException>
An ExceptionInvoker<TException> with the specified
handler.
Exceptions
- ArgumentNullException
handlercannot be null.