Golang---The use of panic and recover

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

In the golang of the wrong handling, I here is the summary of their own practice.

1. Log the error messages to the logs

2, panic, and then use the Recover function for exception capture. (I'm just doing a simple example to record this usage.)

function A calls function B, where you can use recover in function A or in function B

Code to save log information to the log ****************************

Write data to the login log

FileName: The file name to save the log to

Content: What to add to the log

Funcwrite_user_info (filename,contentstring) {

File,err: = os. OpenFile (Filename,os. O_append|os. O_rdwr|os. o_create,0666)

Iferr! = Nil {

Log. Println ("Open file failed ...", err)



Deferfile. Close ()

Usr_time: = time. Now (). Format ("2006-01-02 15:04:05")

Content = Fmt. Sprint (Usr_time, "", Content, "\ r \ n")

_,err = file. WriteString (content)

Iferr! = Nil {

Log. Println ("Write data to log failed ...", err)




Using the panic and recover functions ****************************

Functest_painc (T *testing. T) {

Log. Println (GetInt ())


Funcgetint () int{

Defer func () int{

Iferr: =recover (); Err! = Nil {



Log. Println ("Recover........continue")



Log. Println ("Begin...........begin")

Panic ("Hello Panic")


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.