This is a creation in Article, where the information may have evolved or changed.
PackageMainImport( "FMT""Errors")funcTestpanic2error() (ErrError) { //Capture and recovery panic./ * Note that defer deferred functions can modify the named return value of the peripheral function "Testpanic2error". * Capture panic by calling recover and convert to error. Maybe someone is going to put a defer statement in the main function that captures all the panic exceptions in the program, * Set up the last firewall to prevent the program from crashing, but unfortunately, when the defer delay function of the main function is executed, Also means that the main function to exit, * at this time to capture the panic recovery program, the significance of how much? But we have a way to overcome, to create a "testpanic2error" such as a peripheral encapsulation function, in this function, * Set up the last firewall, like this As in the example code, the panic is enclosed in its own package, and the spread is not allowed to infect other packets, and the packet is passed only by error between the package and the result state. */ defer func() { ifr: =Recover(); r! =Nil{fmt.Println("recovered in Testpanic2error", R)//check exactly what is the panic was and create error. Switchx: = R. (type) { Casestring: Err = errors.New(x) CaseError: Err = xdefault: Err = errors.New("Unknow Panic") } } }() //logic code, panic here.//panic ("I am string")//panic (errors. New ("I am Error")) Panic(-1) returnNil}funcMain() {fmt.Println(Testpanic2error()) fmt.Println("Panic restore now, continue.")}
Note: This article is only my personal notes, if there are errors and omissions, please correct me, study together, my e-mail: htyu_0203_39@sina.com