I have a lot of duplicate code in my program that basically follows this structure:
If condition is true
Create ErrorRecord object
Call ThrowTerminatingError(error object)
End if
The structure of this code is exactly the same for each instance, one of two parameters are different. So for example this is part of one of my methods
protected void ProcessRecord()
{
...
var login = PrivateFunctions.GetLogin(samAccountName);
if (login == null)
{
var errorRecord = new ErrorRecord(
new NullReferenceException($"A login for the user account '{samAccountName}' does not exist in the database."),
"LoginNotFound",
ErrorCategory.ObjectNotFound,
login);
ThrowTerminatingError(errorRecord);
}
var user = PrivateFunctions.GetUser(login);
if (user == null)
{
var errorRecord = new ErrorRecord(
new NullReferenceException($"A user for the login '{login.Name}' does not exist in the database."),
"UserNotFound",
ErrorCategory.ObjectNotFound,
user);
ThrowTerminatingError(errorRecord);
}
...
}
I'm thinking I could create a static method with parameters to create the ErrorObject and initialise it as required. For example:
static internal ErrorObject CreateUserError(Login login)
{
return new ErrorRecord(
new NullReferenceException($"A user for the login '{login.Name}' does not exist in the database."),
"UserNotFound",
ErrorCategory.ObjectNotFound,
user);
}
And then used:
ThrowTerminatingErrorRecord(StaticClass.CreateUserError(login));
Is there a design pattern I could use or is there a better approach?
Edit: In response to the first comment, this is what happens if I throw an exception rather than constructing the error record:
Calling ThrowTerminatingError:
Get-DatabaseUserInformation : "A login for the user account 'domain\username' does not exist in the database."
+ Get-DatabaseUserInformation <<<<
+ CategoryInfo : ObjectNotFound: (:) [Get-DatabaseUserInformation], Exception
+ FullyQualifiedErrorId : "LoginNotFound",Module.Cmdlet
Throwing an exception:
Get-DatabaseUserInformation : An exception was thrown.
+ get-databaseuser <<<<
+ CategoryInfo : NotSpecified: (:) [Get-DatabaseUserInformation], Exception
+ FullyQualifiedErrorId : System.Exception,Module.Cmdlet