Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
namespace ConsoleApp35
{
class Program
{
private static ExceptionHandler _exceptionHandler = new ExceptionHandler();
static async void Main(string[] args)
{
var result = _exceptionHandler.With(() => someEvilShit())
.WithMessageTemplate("The evil struck")
.WithThrowerUpper((msg, ex) => throw new Exceptions.CannotUpload(msg, ex))
.Get();
string someEvilShit()
{
throw new Exception();
}
}
}
internal class ExceptionHandler
{
public ExceptionHandler<T> With<T>(Func<T> function)
{
return new ExceptionHandler<T>(function);
}
}
internal class ExceptionHandler<T>
{
private Func<T> _function;
private Action<string, Exception> _rethrowAction;
private string _messageTemplate;
public ExceptionHandler(Func<T> function)
{
_function = function;
}
public T Get()
{
try
{
return _function.Invoke();
}
catch (Exception ex)
{
var logMessage = string.IsNullOrEmpty(_messageTemplate) ? ex.Message : _messageTemplate;
_log.Error(logMessage, ex);
if (_rethrowAction is { })
{
_rethrowAction.Invoke(logMessage, ex);
}
}
return default;
}
public ExceptionHandler<T> WithMessageTemplate(string template)
{
_messageTemplate = template;
return this;
}
public ExceptionHandler<T> WithThrowerUpper(Action<string, Exception> rethrowAction)
{
_rethrowAction = rethrowAction;
return this;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment