This is a creation in Article, where the information may have evolved or changed. Golang error Handling method has been a lot of people criticized the place, a lot of people spit Groove said half of the code is if err! = Nil {/* ERROR handling */}, seriously affect the normal processing logic, I most open also resent this error handling mechanism, each call to complete a function need check, Custom functions also add a return value for the error type, but a lot of data is slowly understood to understand the benefits of this error mechanism. Because it is possible to invoke each function with errors, it is easier to build complex large systems in a timely manner where errors occur. # # # Exceptions and error errors and exceptions are easily confused, and errors refer to problems where there may be problems, such as the failure to open a file, which is expected, and the exception refers to a problem where the problem should not occur, a situation that has been unexpected. Golang uses Panic,defer,recover to handle exception conditions, similar to the try Catch finially in Java. Throws an exception using panic, throws an exception and immediately stops the execution of the current function and runs all defer functions, then throws the panic up one level until the program Carsh. However, you can also use the defer recover function to catch the crash of the exception blocker, recover only meaningful after being defer. When an HTTP link is received, Golang will call the serve function, and the serve function will parse the HTTP protocol and hand it over to the upper handler, which will be captured by the handler function in defer if an exception is thrown in the upper recover. , print out the current stack information so that an exception to an HTTP request prevents the entire program from crashing. Func (c *conn) serve () {defer func () {if err: = Recover (); Err! = Nil {Const SIZE = << 10buf: = Make ([]byte, size) BUF = Buf[:runtime. Stack (buf, False)]fmt. PRINTLF ("Http:panic serving%v:%v\n%s", c.remoteaddr, Err, BUF)} () W: = C.readrequest () servehttp (W, W.req)} "# # Error handling we can also use some methods to simplify the logic of error handling, and the general idea is to reuse duplicate code. + * * Centralized processing error in defer * * ' func demo ()} { var err error defer func () {if err! = Nil {//Handle error occurred, print log etc information return} } err = Func1 () if err! = nil {return} err = Func2 () if err! = nil {return}. ....} If Golang supports macros, it will be possible if err! = Nil {return} as a macro definition is perfect, but Golang does not support macros. "' + **all-or-nothing check** This is Rob Pike in [Errors rea values] (Https://blog.golang.org/errors-are-values) The method mentioned in this article, If there are multiple small tasks in a complete task, we do not need to perform each small task to check for errors, we can judge the execution of the whole task after all the small tasks are done. '//verbose code, full-text duplicate if Err! = Nil _, err = FD. Write (P0[A:B]) if err! = Nil {return err}_, err = FD. Write (P1[c:d]) if err! = Nil {return err}_, err = FD. Write (P2[e:f]) if err! = Nil {return err}//and so on ' we can simplify the code so that the ' type errwriter struct {w io. Writer err Error}func (ew *errwriter) write (buf []byte) {if ew.err! = Nil {return} _, Ew.err = ew.w. Write (buf)}ew: = &errwriter{w:fd}ew.write (P0[a:b]) ew.write (P1[c:d]) ew.write (p2[e:f])//Only need to check the last time if ew.erR! = Nil {return ew.err}//the obvious problem with this approach is that we don't know if the whole task is going to be an error when a small task is executed, and if we need to focus on the progress of each small task, that's not the way to go. "# #错误上下文error是一个接口, any type that implements the error () function satisfies that interface, errors. New () actually returns a errorstring type that contains only a string string, with no contextual information about the error, and when we throw the error up, we do it uniformly at the top, You can only output a single string of information without knowing where the error occurred and under what circumstances. ' Type Error interface {error () String}type errorstring struct {s string}func (e *errorstring) error () string { return E.s}func New (text string) error {return &errorstring{text}} ' ' Since error is an interface, we can also implement a type that satisfies the interface and record the Files, functions, stacks and other information, more convenient to find the wrong. ' Package Stackerrimport ("FMT" "Runtime" "strings") type Stackerr struct {Filename Stringcallingmethod stringline Interrormessage stringstacktrace string}func New (Err interface{}) *stackerr {var errmessage stringswitch t: = Err . (type) {case *stackerr:return tcase string:errmessage = tcase error:errmessage = T.error () Default:errmessage = Fmt. Sprintf ("%v", t)}stackerr: = &stackerr{}stackerr.errormessage = errmessage_, file, line, OK: = runtime. CAller (1) if OK {stackerr.line = linecomponents: = Strings. Split (file, "/") Stackerr.filename = components[(len (1))]}const size = 1 << 12buf: = Make ([]byte, size) n : = Runtime. Stack (buf, false) Stackerr.stacktrace = string (Buf[:n]) return Stackerr}func (this *stackerr) Error () string {return this. Errormessage}func (This *stackerr) Stack () string {return FMT. Sprintf ("{%s:%d}%s\nstack info:\n%s", this. Filename, this. Line, this. ErrorMessage, this. StackTrace)}func (this *stackerr) Detail () string {return FMT. Sprintf ("{%s:%d}%s", this.) Filename, this. Line, this. errormessage)} "reference [error Handling and go] (http://blog.golang.org/error-handling-and-go) [Go Web programming--11.1 error handling] ( HTTPS://GITHUB.COM/ASTAXIE/BUILD-WEB-APPLICATION-WITH-GOLANG/BLOB/MASTER/ZH/11.1.MD) [Go language error handling (Tony Bai's blog)] ( http://tonybai.com/2015/10/30/error-handling-in-go/) [Errors is values] (https://blog.golang.org/ errors-are-values) [Stackerr Project Source] (Https://github.com/sdbaiguanghe/stackerr)
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service