Skip to content

Instantly share code, notes, and snippets.

@sappho192
Created May 8, 2023 05:36
Show Gist options
  • Save sappho192/066e2a0dc1bc883b82fe73396b3e1594 to your computer and use it in GitHub Desktop.
Save sappho192/066e2a0dc1bc883b82fe73396b3e1594 to your computer and use it in GitHub Desktop.
Thrower pattern
// from https://forum.dotnetdev.kr/t/c-10-null-check-7/7069/2
public static class Thrower
{
public static Exception ThrowIfFailedValidation<T>(T target, Func<T, bool> validation)
{
if (validation(target) is false)
{
throw new ValidationFailedException();
}
}
public static Exception ThrowIfNullOrWhitespace(string? text, string? message)
{
if (string.IsNullOrWhiteSpace(text))
{
throw new TextNullOrWhitespaceException(message);
}
}
public static Exception ThrowForbidden(string message, int resultCode)
{
throw new ForbiddenException(HttpStatusCode.Forbidden, message, resultCode);
}
public static Exception ThrowBadRequest(string message, int resultCode)
{
throw new BadRequestException(HttpStatusCode.BadRequest, message, resultCode);
}
public static Exception Throw500Error(string message, int resultCode)
{
throw new InternalServerErrorException(HttpStatusCode.BadRequest, message, resultCode);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment