Golang - Check Multiple Errors in one Condition

mohammad ali
Sep 22, 2022

Sometimes you want to handle multiple errors in same condition. But it makes mess in your code.

if err1 != nil && err2 != nil && err3 != nil && err4 != nil{
print("Error occured ")
return
}

Obviously we can do this more elegantly. We can create a function to check if errors are nil or not. Just like this:

func AnyErr(errs ...error) error {
for _, e := range errs {
if e != nil {
return e
}
}
return nil
}

Now We can use it like this:

if e:=AnyErr(err1,err2,err3,err4); e != nil {
fmt.printf("Error occured %s",e.Error())
return
}

Looks more cool !!! Right !!!??

--

--

mohammad ali

I write about the solutions to problems i solve at work being Golang developer. If you want to learn along with me as i learn then hit the follow button.