Is function parameter validation using errors a good pattern in Go?

前端 未结 2 1546
执笔经年
执笔经年 2020-12-10 04:09

Is parameter validation using error return codes considered good practice ? I mean where should somebody use errors vs panics (are there any guidelines?).

For instan

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 04:50

    The answer to this is subjective. Here are my thoughts:

    Regarding panic, I like this quote from Go By Example (ref)

    A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully.

    In the description of your use case, I would argue that you should raise an errors and handle the errors. I would further argue that it is good practice to check the error status when one is provided by the function you are using and that the user should check if one is provided in the documentation.

    Panics I would use to stop the execution if I run across an error that is returned from the function you are writing that I check and don't have a way to recover from.

提交回复
热议问题