Go language captures panic anomalies and translates to error

Source: Internet
Author: User
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
Related Article

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.