您的位置 首页 golang

聊聊golang的error包装

本文主要研究一下golang的error包装

聊聊golang的error包装

error

 type error interface {
    Error() string
}
  

runtime.Error

 package runtime

type Error interface {
    error
    // and perhaps other methods
}
  

对于panic,产生的则是runtime.Error,该接口内嵌了error接口

wrap

 package main

import (
    "errors"
    "fmt"

    pkgerr "github.com/pkg/errors"
)

func main() {
    if err := methodA(false); err != nil {
        fmt.Printf("%+v", err)
    }
    if err := methodA(true); err != nil {
        fmt.Printf("%+v", err)
    }
}

func methodA(wrap bool) error {
    if err := methodB(wrap); err != nil {
        if wrap {
            return pkgerr.Wrap(err, "methodA call methodB error")
        }
        return err
    }
    return nil
}

func methodB(wrap bool) error {
    if err := methodC(); err != nil {
        if wrap {
            return pkgerr.Wrap(err, "methodB call methodC error")
        }
        return err
    }
    return nil
}

func methodC() error {
    return errors.New("test error stack")
}
  

使用内置的errors,则没办法打印堆栈;使用pkg/errors可以携带堆栈

输出

 test error stack
test error stack
methodB call methodC error
main.methodB
        /error-demo/error_wrap.go:33
main.methodA
        /error-demo/error_wrap.go:21
main.main
        /error-demo/error_wrap.go:15
runtime.main
        /usr/local/go/src/runtime/proc.go:204
runtime.goexit
        /usr/local/go/src/runtime/asm_amd64.s:1374
methodA call methodB error
main.methodA
        /error-demo/error_wrap.go:23
main.main
        /error-demo/error_wrap.go:15
runtime.main
        /usr/local/go/src/runtime/proc.go:204
runtime.goexit
        /usr/local/go/src/runtime/asm_amd64.s:1374% 
  

小结

  • error接口定义了Error方法,返回string;对于panic,产生的则是runtime.Error,该接口内嵌了error接口
  • 使用内置的errors,则没办法打印堆栈;使用pkg/errors可以携带堆栈

doc

  • Errors
  • pkg/errors
  • Embedding Interfaces in Go (Golang)

文章来源:智云一二三科技

文章标题:聊聊golang的error包装

文章地址:https://www.zhihuclub.com/100053.shtml

关于作者: 智云科技

热门文章

评论已关闭

30条评论

  1. Brandon Moss RBI double was one of seven hits given up by Richards, who struck out six and walked two

  2. Unlike the process of spermatogenesis, the secondary oocyte does not undergo its second meiotic division until after fertilization has occurred furadantin rohpharm pharmacy The man reading the statement was not immediately identifiable to Reuters, but the video was posted on several of the social media pages belonging to groups said to have signed on to it, such as the Tawheed brigade

  3. For ovarian cancer At least 2 cups per day has been used Altogether, these results indicate that TLX1 may repress RA signaling in the SPM, possibly through the control of Cyp26b1 expression and RA degradation

  4. Wood ME, Stockdale A, Flynn BS In contrast, commercial grade carrageenan supplied by Sigma is a pure carrageenan which involved alkali treatment, hot extraction, filtration, KCl precipitation or alcohol precipitation, dehydration, dried and then milled to get carrageenan powder 46

  5. minocin super avana review When asked how he would respond to anyone who accused the sitcom of being racist or homophobic, he said I d tell you straight away, they don t know their history they don t understand their history and they don t know anything about the British Empire Adverse reactions experienced Some common side effects seen in patients taking Ribavirin are skin rash, fatigue, headache, birth defects, and anemia low red blood cell count

  6. The corpse of the young bipedal dragon can allergy medicine alter blood pressure in front blood pressure medication deltyazim of vitamkns to lower blood pressure him is medication blood pressure with an h just right here, except for the fat pig, who would be so immoral There was also a selective expression of the endoplasmic reticulum stress chaperone GRP78 and activated caspase 3 at these sites after incubation with cytotoxic concentrations of tamoxifen 10 100 ОјM

  7. QTc interval 480 msec based on the mean value of the triplicate ECGs, family or personal history of long or short QT syndrome, Brugada syndrome or known history of QTc prolongation or Torsade de Pointes

  8. Some commonly used anticoagulants include heparin, sodium, potassium, or lithium ethylenediaminetetraacetic acid EDTA, citrate, and oxalate salts

  9. In Fact, The Keto Food Plan Is Unlikely To Negatively Impact Your Levels Of Cholesterol Despite Being So Excessive In Fats Moreover, It S Capable Of Reducing Cardiovascular Disease Danger Components, Particularly In Those Who Are Obese Following A Ketogenic Food Regimen Modifications Your Fuel Supply From One Which Primarily Burns Carbohydrates To One That Burns Fat, Says Olivia Wagner, Rdn, A Practical Dietitian At Liv Nourished In Chicago Now, Let S Get Into Which Meals You Ll Be Having Fun With Most Frequently On The Keto Food Regimen, Which Meals You Possibly Can Eat Often And Which Meals Are Off Limits So You Will Get Started In Your Very Personal Ketogenic Food Plan Meal Plan

  10. Many times when a Day 3 FSH test comes back unexpectedly high, a physician may choose to repeat this test or a patient may request that it be repeated

  11. started out with 20mg twice a day, then up to 80mg Crystalline forms of 4 2, 6 dichloro benzoylamino 1H pyrazole 3 carboxylic acid 1 methanesulphonyl piperidin 4 yl amide are disclosed in our applications U

  12. In the absence of the effective treatment for HCC, innovative chemopreventive approaches may efficiently reduce the prevailing morbidity and mortality

网站地图