Is GetLastError() kind of design pattern? Is it good mechanism?

前端 未结 7 1948
庸人自扰
庸人自扰 2021-02-12 15:27

Windows APIs uses GetLastError() mechanism to retrieve information about an error or failure. I am considering the same mechanism to handle errors as I am writing A

相关标签:
7条回答
  • 2021-02-12 16:16

    I think GetLastError is a relic from the days before multi-threading. I don't think that pattern should be used any more except in cases where errors are extraordinarily rare. The problem is that the error code has to be per-thread.

    The other irritation with GetLastError is that it requires two levels of testing. You first have to check the return code to see if it indicates an error and then you have to call GetLastError to get the error. This means you have to do one of two things, neither particularly elegant:

    1) You can return a boolean indicating success or failure. But then, why not just return the error code with zero for success?

    2) You can have a different return value test for each function based on a value that is illegal as its primary return value. But then what of functions where any return value is legal? And this is a very error-prone design pattern. (Zero is the only illegal value for some functions, so you return zero for error in that case. But where zero is legal, you may need to use -1 or some such. It's easy to get this test wrong.)

    0 讨论(0)
提交回复
热议问题