Function Output

Welcome Forums General PowerShell Q&A Function Output

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
1 year, 4 months ago.

  • Author
    Posts
  • #81571

    Participant
    Points: 0
    Rank: Member

    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

    Keymaster
    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    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

    Participant
    Points: 0
    Rank: Member

    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?

The topic ‘Function Output’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort