Author Posts

October 9, 2017 at 10:11 am

Does anyone disagree with the following?

Functions should return an object or throw an exception (to fit in with Don's controller/tool distinction and to allow easier unit testing).

I'm seeing functions that don't return anything, and all exceptions are in an internal catch block which logs the error, but I think it makes the function harder to unit test.

Any opinions?

October 9, 2017 at 1:55 pm

Well, it depends.

Functions should obey their -ErrorAction parameter. Meaning, you should write an error if you can possibly continue, using Write-Error, rather than Throw. That way, -ErrorAction will function properly. By default, it'll just Continue, but if I'm using the function and want to trap the problem, I can specify Stop and do so on my own.

A lot of people want to completely hide/consume their errors, which I generally disagree with. If I'm using your function and I want error logging, I should be able to deal with that logging on my own, not have fifty different logging mechanisms for every function I choose to use. People do this because they're used to _scripting_, not _toolmaking_. If you look at .NET itself, classes don't attempt to consume/hide their errors, and that's the pattern we should ideally be following for functions in PowerShell.

October 9, 2017 at 2:48 pm

Thanks Don. In the scenario that a function accepts an array to iterate over, would you consume/log any errors and instead return an array object containing the result of error operation?