Skip to content

Instantly share code, notes, and snippets.

@davidwengier
Created September 22, 2020 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidwengier/b6124850548bb1af992ccc48eab9bc6b to your computer and use it in GitHub Desktop.
Save davidwengier/b6124850548bb1af992ccc48eab9bc6b to your computer and use it in GitHub Desktop.
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