How to handle multiple errors in go?Error handling in C codeAsyncTask and error handling on AndroidConvert string to integer type in Go?What are the best practices for JavaScript error handling?Go Error Handling when Returning StructsMultiple values in single-value contextIs it idiomatic in go to handle all returned errors?Is it bad practice to reset an error in golang?Understanding error handling in NodeJs, ExpressJs and MongooseWhat is the idiomatic way to handle nil and error in Golang?

Examples of subgroups where it's nontrivial to show closure under multiplication?

US visa is under administrative processing, I need the passport back ASAP

Critique of timeline aesthetic

what is the sudo password for a --disabled-password user

How can I place the product on a social media post better?

How can I practically buy stocks?

What route did the Hindenburg take when traveling from Germany to the U.S.?

To say I met a person for the first time

How to pronounce 'C++' in Spanish

Why do games have consumables?

How to creep the reader out with what seems like a normal person?

A ​Note ​on ​N!

Examples of non trivial equivalence relations , I mean equivalence relations without the expression " same ... as" in their definition?

Is it idiomatic to construct against `this`?

Realistic Necromancy?

What language was spoken in East Asia before Proto-Turkic?

In order to check if a field is required or not, is the result of isNillable method sufficient?

how to find the equation of a circle given points of the circle

Do I have an "anti-research" personality?

Was there a Viking Exchange as well as a Columbian one?

Why was the Spitfire's elliptical wing almost uncopied by other aircraft of World War 2?

Size of electromagnet needed to replicate Earth's magnetic field

Why does processed meat contain preservatives, while canned fish needs not?

Is the claim "Employers won't employ people with no 'social media presence'" realistic?



How to handle multiple errors in go?


Error handling in C codeAsyncTask and error handling on AndroidConvert string to integer type in Go?What are the best practices for JavaScript error handling?Go Error Handling when Returning StructsMultiple values in single-value contextIs it idiomatic in go to handle all returned errors?Is it bad practice to reset an error in golang?Understanding error handling in NodeJs, ExpressJs and MongooseWhat is the idiomatic way to handle nil and error in Golang?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















What is the most idiomatic way to handle multiple errors in go?



Should I try to wrap the error and return both?



if err := foo(bar, obj); err != nil 
// how to do I avoid losing this error?
err := l.fixup(obj)
if err != nil
// but this error is the not the one from foo?

return err

return l.fixup(obj)









share|improve this question
























  • Your first line is an example of what you can do, put in in a new block scope. Is there a reason you're not doing that?

    – JimB
    Mar 22 at 18:16












  • There is a dependency on foo. If foo fails then fixup needs to see that. Fixup has to be called regardless after foo but has different behaviors based on the result of foo. Really, I want to see the err from foo since that indicates a problem, fixup isn't expected to fail

    – PythonCowboy
    Mar 22 at 18:24







  • 1





    Then why not name them differently? The obvious solution is usually acceptable.

    – JimB
    Mar 22 at 18:30


















0















What is the most idiomatic way to handle multiple errors in go?



Should I try to wrap the error and return both?



if err := foo(bar, obj); err != nil 
// how to do I avoid losing this error?
err := l.fixup(obj)
if err != nil
// but this error is the not the one from foo?

return err

return l.fixup(obj)









share|improve this question
























  • Your first line is an example of what you can do, put in in a new block scope. Is there a reason you're not doing that?

    – JimB
    Mar 22 at 18:16












  • There is a dependency on foo. If foo fails then fixup needs to see that. Fixup has to be called regardless after foo but has different behaviors based on the result of foo. Really, I want to see the err from foo since that indicates a problem, fixup isn't expected to fail

    – PythonCowboy
    Mar 22 at 18:24







  • 1





    Then why not name them differently? The obvious solution is usually acceptable.

    – JimB
    Mar 22 at 18:30














0












0








0








What is the most idiomatic way to handle multiple errors in go?



Should I try to wrap the error and return both?



if err := foo(bar, obj); err != nil 
// how to do I avoid losing this error?
err := l.fixup(obj)
if err != nil
// but this error is the not the one from foo?

return err

return l.fixup(obj)









share|improve this question
















What is the most idiomatic way to handle multiple errors in go?



Should I try to wrap the error and return both?



if err := foo(bar, obj); err != nil 
// how to do I avoid losing this error?
err := l.fixup(obj)
if err != nil
// but this error is the not the one from foo?

return err

return l.fixup(obj)






go error-handling






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 15:52









Nik

1,144617




1,144617










asked Mar 22 at 18:08









PythonCowboyPythonCowboy

31




31












  • Your first line is an example of what you can do, put in in a new block scope. Is there a reason you're not doing that?

    – JimB
    Mar 22 at 18:16












  • There is a dependency on foo. If foo fails then fixup needs to see that. Fixup has to be called regardless after foo but has different behaviors based on the result of foo. Really, I want to see the err from foo since that indicates a problem, fixup isn't expected to fail

    – PythonCowboy
    Mar 22 at 18:24







  • 1





    Then why not name them differently? The obvious solution is usually acceptable.

    – JimB
    Mar 22 at 18:30


















  • Your first line is an example of what you can do, put in in a new block scope. Is there a reason you're not doing that?

    – JimB
    Mar 22 at 18:16












  • There is a dependency on foo. If foo fails then fixup needs to see that. Fixup has to be called regardless after foo but has different behaviors based on the result of foo. Really, I want to see the err from foo since that indicates a problem, fixup isn't expected to fail

    – PythonCowboy
    Mar 22 at 18:24







  • 1





    Then why not name them differently? The obvious solution is usually acceptable.

    – JimB
    Mar 22 at 18:30

















Your first line is an example of what you can do, put in in a new block scope. Is there a reason you're not doing that?

– JimB
Mar 22 at 18:16






Your first line is an example of what you can do, put in in a new block scope. Is there a reason you're not doing that?

– JimB
Mar 22 at 18:16














There is a dependency on foo. If foo fails then fixup needs to see that. Fixup has to be called regardless after foo but has different behaviors based on the result of foo. Really, I want to see the err from foo since that indicates a problem, fixup isn't expected to fail

– PythonCowboy
Mar 22 at 18:24






There is a dependency on foo. If foo fails then fixup needs to see that. Fixup has to be called regardless after foo but has different behaviors based on the result of foo. Really, I want to see the err from foo since that indicates a problem, fixup isn't expected to fail

– PythonCowboy
Mar 22 at 18:24





1




1





Then why not name them differently? The obvious solution is usually acceptable.

– JimB
Mar 22 at 18:30






Then why not name them differently? The obvious solution is usually acceptable.

– JimB
Mar 22 at 18:30













4 Answers
4






active

oldest

votes


















1














You can add a context to your original error using Wrap function from this great package from Dave Cheney
https://github.com/pkg/errors



errors.Wrap function returns a new error that adds context to the original error.



func Wrap(cause error, message string) error


in your case this would be:



if cause := foo(bar, obj); cause != nil 
err := l.fixup(obj)
if err != nil
return errors.Wrap(cause, err.Error())

return cause

return l.fixup(obj)





share|improve this answer























  • Thanks! This is what decided to go with

    – PythonCowboy
    Mar 22 at 22:08











  • Please accept the answer if this works for you ;)

    – Nik
    Mar 28 at 11:41


















0














The fixup method is called in both code paths in the question. Simplify the code by calling fixup outside the if statement.



If you want the error from foo to take precedence over the error from fixup, then do just that.



err1 := foo(bar, obj)
err2 := l.fixup(obj)
if err1 != nil
return err1

return err2





share|improve this answer






























    0














    You code calls l.fixup(obj) no matter what. If foo(bar, obj) returns an error, some handling is done and l.fixup(obj) is called - otherwise only l.fixup(obj) is called. Hence, your code can be rearranged like this:



    // err will only be valid within the if-then-else-construct
    if err := foo(bar, obj); err != nil
    // handle error from foo(bar,obj)
    // you can even return it, if you wanted to
    // For the sake of this example, we simply log it
    log.Println("Executing foo: %s", err)

    return l.fixup(obj)


    Furthermore, you can use the fact that error is an interface to your advantage if you want to distinguish between the error potentially returned by foo or l.fixup. You can do that by creating a typed error for one (or both of them) and evaluate the type of the error by using what is called a type switch.



    package main

    import (
    "errors"
    "fmt"
    )

    // FooError is the error to be returned by foo
    type FooError struct
    Bar string


    // Error implements the interface
    func (f FooError) Error() string
    return fmt.Sprintf("%s: interface is nil", f.Bar)


    // dummy foo func
    func foo(bar string, in interface) error
    if in == nil
    return FooErrorBar: bar

    return nil


    // dummy fixup func
    func fixup(in interface) error
    if in == nil
    return errors.New("Interface is nil")

    return nil


    // a wrapper, containing a variation of above code
    func wrap(bar string) error
    if err := foo(bar, nil); err != nil
    // handle error from foo(bar,obj)
    // you can even return it, if you wanted to
    return err

    return fixup(nil)


    func main()
    err := wrap("test")

    // The type switch itself
    switch err.(type)
    case FooError:
    // We have a FooError, so we can deal with it accordingly
    fmt.Println("Foo Error:",err)
    default:
    // Every other error is handled by the default block
    fmt.Println("Std Error:",err)




    However, this does not feel quite right. If foo is called and it returning an error prevents something else in your logic not being executed, it might be valid to panic instead.






    share|improve this answer






























      0














      If you must chain errors and return, it all depends what your error means and which one you want to notify the caller of. Usually, when the occurence of an error should not stop the path and a call follows, such as foo here then fixup, you'd log the first error and return the second one, as it is probably the most relevant to what your function does.



      There are also packages to wrap errors, so that you can build an error from multiple errors.



      There is the standard package with fmt.Errorf you could assemble multiple errors.



      There is also https://github.com/hashicorp/go-multierror which allows you to keep multiple errors in an error.



      In your case, if you want to get both error messages to bubble up, I'd do something like that:



      err := foo(bar, obj)

      if fixupErr := l.fixup(obj); fixupErr != nil
      if err != nil
      return fmt.Errorf("foo err: %snfixup err: %sn", err, fixupErr)

      return fixupErr

      return err





      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55305523%2fhow-to-handle-multiple-errors-in-go%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        You can add a context to your original error using Wrap function from this great package from Dave Cheney
        https://github.com/pkg/errors



        errors.Wrap function returns a new error that adds context to the original error.



        func Wrap(cause error, message string) error


        in your case this would be:



        if cause := foo(bar, obj); cause != nil 
        err := l.fixup(obj)
        if err != nil
        return errors.Wrap(cause, err.Error())

        return cause

        return l.fixup(obj)





        share|improve this answer























        • Thanks! This is what decided to go with

          – PythonCowboy
          Mar 22 at 22:08











        • Please accept the answer if this works for you ;)

          – Nik
          Mar 28 at 11:41















        1














        You can add a context to your original error using Wrap function from this great package from Dave Cheney
        https://github.com/pkg/errors



        errors.Wrap function returns a new error that adds context to the original error.



        func Wrap(cause error, message string) error


        in your case this would be:



        if cause := foo(bar, obj); cause != nil 
        err := l.fixup(obj)
        if err != nil
        return errors.Wrap(cause, err.Error())

        return cause

        return l.fixup(obj)





        share|improve this answer























        • Thanks! This is what decided to go with

          – PythonCowboy
          Mar 22 at 22:08











        • Please accept the answer if this works for you ;)

          – Nik
          Mar 28 at 11:41













        1












        1








        1







        You can add a context to your original error using Wrap function from this great package from Dave Cheney
        https://github.com/pkg/errors



        errors.Wrap function returns a new error that adds context to the original error.



        func Wrap(cause error, message string) error


        in your case this would be:



        if cause := foo(bar, obj); cause != nil 
        err := l.fixup(obj)
        if err != nil
        return errors.Wrap(cause, err.Error())

        return cause

        return l.fixup(obj)





        share|improve this answer













        You can add a context to your original error using Wrap function from this great package from Dave Cheney
        https://github.com/pkg/errors



        errors.Wrap function returns a new error that adds context to the original error.



        func Wrap(cause error, message string) error


        in your case this would be:



        if cause := foo(bar, obj); cause != nil 
        err := l.fixup(obj)
        if err != nil
        return errors.Wrap(cause, err.Error())

        return cause

        return l.fixup(obj)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 21:36









        NikNik

        1,144617




        1,144617












        • Thanks! This is what decided to go with

          – PythonCowboy
          Mar 22 at 22:08











        • Please accept the answer if this works for you ;)

          – Nik
          Mar 28 at 11:41

















        • Thanks! This is what decided to go with

          – PythonCowboy
          Mar 22 at 22:08











        • Please accept the answer if this works for you ;)

          – Nik
          Mar 28 at 11:41
















        Thanks! This is what decided to go with

        – PythonCowboy
        Mar 22 at 22:08





        Thanks! This is what decided to go with

        – PythonCowboy
        Mar 22 at 22:08













        Please accept the answer if this works for you ;)

        – Nik
        Mar 28 at 11:41





        Please accept the answer if this works for you ;)

        – Nik
        Mar 28 at 11:41













        0














        The fixup method is called in both code paths in the question. Simplify the code by calling fixup outside the if statement.



        If you want the error from foo to take precedence over the error from fixup, then do just that.



        err1 := foo(bar, obj)
        err2 := l.fixup(obj)
        if err1 != nil
        return err1

        return err2





        share|improve this answer



























          0














          The fixup method is called in both code paths in the question. Simplify the code by calling fixup outside the if statement.



          If you want the error from foo to take precedence over the error from fixup, then do just that.



          err1 := foo(bar, obj)
          err2 := l.fixup(obj)
          if err1 != nil
          return err1

          return err2





          share|improve this answer

























            0












            0








            0







            The fixup method is called in both code paths in the question. Simplify the code by calling fixup outside the if statement.



            If you want the error from foo to take precedence over the error from fixup, then do just that.



            err1 := foo(bar, obj)
            err2 := l.fixup(obj)
            if err1 != nil
            return err1

            return err2





            share|improve this answer













            The fixup method is called in both code paths in the question. Simplify the code by calling fixup outside the if statement.



            If you want the error from foo to take precedence over the error from fixup, then do just that.



            err1 := foo(bar, obj)
            err2 := l.fixup(obj)
            if err1 != nil
            return err1

            return err2






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 22 at 18:32









            Cerise LimónCerise Limón

            56k57395




            56k57395





















                0














                You code calls l.fixup(obj) no matter what. If foo(bar, obj) returns an error, some handling is done and l.fixup(obj) is called - otherwise only l.fixup(obj) is called. Hence, your code can be rearranged like this:



                // err will only be valid within the if-then-else-construct
                if err := foo(bar, obj); err != nil
                // handle error from foo(bar,obj)
                // you can even return it, if you wanted to
                // For the sake of this example, we simply log it
                log.Println("Executing foo: %s", err)

                return l.fixup(obj)


                Furthermore, you can use the fact that error is an interface to your advantage if you want to distinguish between the error potentially returned by foo or l.fixup. You can do that by creating a typed error for one (or both of them) and evaluate the type of the error by using what is called a type switch.



                package main

                import (
                "errors"
                "fmt"
                )

                // FooError is the error to be returned by foo
                type FooError struct
                Bar string


                // Error implements the interface
                func (f FooError) Error() string
                return fmt.Sprintf("%s: interface is nil", f.Bar)


                // dummy foo func
                func foo(bar string, in interface) error
                if in == nil
                return FooErrorBar: bar

                return nil


                // dummy fixup func
                func fixup(in interface) error
                if in == nil
                return errors.New("Interface is nil")

                return nil


                // a wrapper, containing a variation of above code
                func wrap(bar string) error
                if err := foo(bar, nil); err != nil
                // handle error from foo(bar,obj)
                // you can even return it, if you wanted to
                return err

                return fixup(nil)


                func main()
                err := wrap("test")

                // The type switch itself
                switch err.(type)
                case FooError:
                // We have a FooError, so we can deal with it accordingly
                fmt.Println("Foo Error:",err)
                default:
                // Every other error is handled by the default block
                fmt.Println("Std Error:",err)




                However, this does not feel quite right. If foo is called and it returning an error prevents something else in your logic not being executed, it might be valid to panic instead.






                share|improve this answer



























                  0














                  You code calls l.fixup(obj) no matter what. If foo(bar, obj) returns an error, some handling is done and l.fixup(obj) is called - otherwise only l.fixup(obj) is called. Hence, your code can be rearranged like this:



                  // err will only be valid within the if-then-else-construct
                  if err := foo(bar, obj); err != nil
                  // handle error from foo(bar,obj)
                  // you can even return it, if you wanted to
                  // For the sake of this example, we simply log it
                  log.Println("Executing foo: %s", err)

                  return l.fixup(obj)


                  Furthermore, you can use the fact that error is an interface to your advantage if you want to distinguish between the error potentially returned by foo or l.fixup. You can do that by creating a typed error for one (or both of them) and evaluate the type of the error by using what is called a type switch.



                  package main

                  import (
                  "errors"
                  "fmt"
                  )

                  // FooError is the error to be returned by foo
                  type FooError struct
                  Bar string


                  // Error implements the interface
                  func (f FooError) Error() string
                  return fmt.Sprintf("%s: interface is nil", f.Bar)


                  // dummy foo func
                  func foo(bar string, in interface) error
                  if in == nil
                  return FooErrorBar: bar

                  return nil


                  // dummy fixup func
                  func fixup(in interface) error
                  if in == nil
                  return errors.New("Interface is nil")

                  return nil


                  // a wrapper, containing a variation of above code
                  func wrap(bar string) error
                  if err := foo(bar, nil); err != nil
                  // handle error from foo(bar,obj)
                  // you can even return it, if you wanted to
                  return err

                  return fixup(nil)


                  func main()
                  err := wrap("test")

                  // The type switch itself
                  switch err.(type)
                  case FooError:
                  // We have a FooError, so we can deal with it accordingly
                  fmt.Println("Foo Error:",err)
                  default:
                  // Every other error is handled by the default block
                  fmt.Println("Std Error:",err)




                  However, this does not feel quite right. If foo is called and it returning an error prevents something else in your logic not being executed, it might be valid to panic instead.






                  share|improve this answer

























                    0












                    0








                    0







                    You code calls l.fixup(obj) no matter what. If foo(bar, obj) returns an error, some handling is done and l.fixup(obj) is called - otherwise only l.fixup(obj) is called. Hence, your code can be rearranged like this:



                    // err will only be valid within the if-then-else-construct
                    if err := foo(bar, obj); err != nil
                    // handle error from foo(bar,obj)
                    // you can even return it, if you wanted to
                    // For the sake of this example, we simply log it
                    log.Println("Executing foo: %s", err)

                    return l.fixup(obj)


                    Furthermore, you can use the fact that error is an interface to your advantage if you want to distinguish between the error potentially returned by foo or l.fixup. You can do that by creating a typed error for one (or both of them) and evaluate the type of the error by using what is called a type switch.



                    package main

                    import (
                    "errors"
                    "fmt"
                    )

                    // FooError is the error to be returned by foo
                    type FooError struct
                    Bar string


                    // Error implements the interface
                    func (f FooError) Error() string
                    return fmt.Sprintf("%s: interface is nil", f.Bar)


                    // dummy foo func
                    func foo(bar string, in interface) error
                    if in == nil
                    return FooErrorBar: bar

                    return nil


                    // dummy fixup func
                    func fixup(in interface) error
                    if in == nil
                    return errors.New("Interface is nil")

                    return nil


                    // a wrapper, containing a variation of above code
                    func wrap(bar string) error
                    if err := foo(bar, nil); err != nil
                    // handle error from foo(bar,obj)
                    // you can even return it, if you wanted to
                    return err

                    return fixup(nil)


                    func main()
                    err := wrap("test")

                    // The type switch itself
                    switch err.(type)
                    case FooError:
                    // We have a FooError, so we can deal with it accordingly
                    fmt.Println("Foo Error:",err)
                    default:
                    // Every other error is handled by the default block
                    fmt.Println("Std Error:",err)




                    However, this does not feel quite right. If foo is called and it returning an error prevents something else in your logic not being executed, it might be valid to panic instead.






                    share|improve this answer













                    You code calls l.fixup(obj) no matter what. If foo(bar, obj) returns an error, some handling is done and l.fixup(obj) is called - otherwise only l.fixup(obj) is called. Hence, your code can be rearranged like this:



                    // err will only be valid within the if-then-else-construct
                    if err := foo(bar, obj); err != nil
                    // handle error from foo(bar,obj)
                    // you can even return it, if you wanted to
                    // For the sake of this example, we simply log it
                    log.Println("Executing foo: %s", err)

                    return l.fixup(obj)


                    Furthermore, you can use the fact that error is an interface to your advantage if you want to distinguish between the error potentially returned by foo or l.fixup. You can do that by creating a typed error for one (or both of them) and evaluate the type of the error by using what is called a type switch.



                    package main

                    import (
                    "errors"
                    "fmt"
                    )

                    // FooError is the error to be returned by foo
                    type FooError struct
                    Bar string


                    // Error implements the interface
                    func (f FooError) Error() string
                    return fmt.Sprintf("%s: interface is nil", f.Bar)


                    // dummy foo func
                    func foo(bar string, in interface) error
                    if in == nil
                    return FooErrorBar: bar

                    return nil


                    // dummy fixup func
                    func fixup(in interface) error
                    if in == nil
                    return errors.New("Interface is nil")

                    return nil


                    // a wrapper, containing a variation of above code
                    func wrap(bar string) error
                    if err := foo(bar, nil); err != nil
                    // handle error from foo(bar,obj)
                    // you can even return it, if you wanted to
                    return err

                    return fixup(nil)


                    func main()
                    err := wrap("test")

                    // The type switch itself
                    switch err.(type)
                    case FooError:
                    // We have a FooError, so we can deal with it accordingly
                    fmt.Println("Foo Error:",err)
                    default:
                    // Every other error is handled by the default block
                    fmt.Println("Std Error:",err)




                    However, this does not feel quite right. If foo is called and it returning an error prevents something else in your logic not being executed, it might be valid to panic instead.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 22 at 18:49









                    Markus W MahlbergMarkus W Mahlberg

                    12.7k54062




                    12.7k54062





















                        0














                        If you must chain errors and return, it all depends what your error means and which one you want to notify the caller of. Usually, when the occurence of an error should not stop the path and a call follows, such as foo here then fixup, you'd log the first error and return the second one, as it is probably the most relevant to what your function does.



                        There are also packages to wrap errors, so that you can build an error from multiple errors.



                        There is the standard package with fmt.Errorf you could assemble multiple errors.



                        There is also https://github.com/hashicorp/go-multierror which allows you to keep multiple errors in an error.



                        In your case, if you want to get both error messages to bubble up, I'd do something like that:



                        err := foo(bar, obj)

                        if fixupErr := l.fixup(obj); fixupErr != nil
                        if err != nil
                        return fmt.Errorf("foo err: %snfixup err: %sn", err, fixupErr)

                        return fixupErr

                        return err





                        share|improve this answer





























                          0














                          If you must chain errors and return, it all depends what your error means and which one you want to notify the caller of. Usually, when the occurence of an error should not stop the path and a call follows, such as foo here then fixup, you'd log the first error and return the second one, as it is probably the most relevant to what your function does.



                          There are also packages to wrap errors, so that you can build an error from multiple errors.



                          There is the standard package with fmt.Errorf you could assemble multiple errors.



                          There is also https://github.com/hashicorp/go-multierror which allows you to keep multiple errors in an error.



                          In your case, if you want to get both error messages to bubble up, I'd do something like that:



                          err := foo(bar, obj)

                          if fixupErr := l.fixup(obj); fixupErr != nil
                          if err != nil
                          return fmt.Errorf("foo err: %snfixup err: %sn", err, fixupErr)

                          return fixupErr

                          return err





                          share|improve this answer



























                            0












                            0








                            0







                            If you must chain errors and return, it all depends what your error means and which one you want to notify the caller of. Usually, when the occurence of an error should not stop the path and a call follows, such as foo here then fixup, you'd log the first error and return the second one, as it is probably the most relevant to what your function does.



                            There are also packages to wrap errors, so that you can build an error from multiple errors.



                            There is the standard package with fmt.Errorf you could assemble multiple errors.



                            There is also https://github.com/hashicorp/go-multierror which allows you to keep multiple errors in an error.



                            In your case, if you want to get both error messages to bubble up, I'd do something like that:



                            err := foo(bar, obj)

                            if fixupErr := l.fixup(obj); fixupErr != nil
                            if err != nil
                            return fmt.Errorf("foo err: %snfixup err: %sn", err, fixupErr)

                            return fixupErr

                            return err





                            share|improve this answer















                            If you must chain errors and return, it all depends what your error means and which one you want to notify the caller of. Usually, when the occurence of an error should not stop the path and a call follows, such as foo here then fixup, you'd log the first error and return the second one, as it is probably the most relevant to what your function does.



                            There are also packages to wrap errors, so that you can build an error from multiple errors.



                            There is the standard package with fmt.Errorf you could assemble multiple errors.



                            There is also https://github.com/hashicorp/go-multierror which allows you to keep multiple errors in an error.



                            In your case, if you want to get both error messages to bubble up, I'd do something like that:



                            err := foo(bar, obj)

                            if fixupErr := l.fixup(obj); fixupErr != nil
                            if err != nil
                            return fmt.Errorf("foo err: %snfixup err: %sn", err, fixupErr)

                            return fixupErr

                            return err






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Mar 23 at 4:17

























                            answered Mar 22 at 18:49









                            François P.François P.

                            2,120716




                            2,120716



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55305523%2fhow-to-handle-multiple-errors-in-go%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해