0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Golangのerrorとpanic

Last updated at Posted at 2020-10-12

The art of programing

業務ロジックにエラーブロックが沢山の場合がよく見られる
例えば以下の関数を順次に呼ぶ

func first() error {return nil}
func second() error {return nil}
func third() error {return nil}
func fourth() error {return nil}
func fifth() error {return nil}

errorを判断する書き方は、
なに?眩暈しちゃった。。。

func Do() error {
    var err error
    if err = first(); err == nil {
        if err = second(); err == nil {
            if err = third(); err == nil {
                if err = fourth(); err == nil {
                    if err = fifth(); err == nil {
                        return nil
                    }
                }
            }
        }
    }
    return err
}

実際の仕事にはフラットな方が多くて、

func Do() error {
    var err error
    if err = first(); err != nil {
        return err
    }
    if err = second(); err != nil {
        return err
    }
    if err = third(); err != nil {
        return err
    }
    if err = fourth(); err != nil {
        return err
    }
    if err = fifth(); err != nil {
        return err
    }
    return nil
}

さ、panicを使えば、

func Do2() (err error) {
    defer func(){
        if r:= recover() ; r!= nil{
            err = fmt.Errorf("Error: %+v", r)
        }
    }()
    first2()
    second2()
    third2()
    fourth2()
    fifth2()
    return
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?