sequence
Whatever the language, handling errors is not a hard thing, but each wanted to write compliant error handling is not an easy task. I just I think some of the programming process for handling errors and lessons learned, and certainly not all right, if you think I'm wrong or you have a better way, please feel free.
A. Please do not ignore any errors
At any time we should not ignore the error, most errors are required to capture the process, unless it can tolerate some minor mistakes can be printed out, but it must not be ignored, otherwise maintenance will bring great difficulties
II. I need a dictionary error
Whether you are using the wrong code or abnormal capture error, the error needs to be classified, such as 50x belongs server error, 40x belong to client error
III. Do not write a lot of code in a try catch inside
We hope to complete a try catch only one thing
IV. More is not recommended in the body of the loop processing error
Loop body can be placed within a try statement, then do catch out
V. handling errors as much as possible where the error occurred
This allows the caller easier, if you wrote a go, you know if err! = Nil of embarrassment
VI. Anomaly is not expected to handle what happened, and the error code is handling what might happen
So do not to deal with business logic to handle errors in a logical manner, similar to if (illegal parameter) {} can be done well
VII. Kept on being given a place, do not always print
This log file is too large, it will submerge other error, printing errors, and the number of occurrences can be
VIII. Distinguish the wrong level
General error will let people know what to do, such as fatal represents a major error, error means that the resource or needs are not met, waring is not necessarily a mistake, but require attention, info represents not only an error message, and debug in the development phase Print he should not appear in a production environment
IX. Provide clear documentation for your mistakes as well as the definition of each error code sample
If that, not much to say, we should demonstrate to others the interface for handling errors
X. When handling errors, always clean up resources allocated
E.g. close the stream, finally, and good handling can defer
XI. Error log output error code is preferably used, instead of an error message
This allows the log analysis software is easy to do automated monitoring, rather than doing semantic analysis from the error message