Function Output

This topic contains 2 replies, has 2 voices, and was last updated by  Dave Brannan 1 week, 2 days ago.

  • Author
    Posts
  • #81571

    Dave Brannan
    Participant

    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?

  • #81598

    Don Jones
    Keymaster

    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.

  • #81617

    Dave Brannan
    Participant

    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?

You must be logged in to reply to this topic.