Hello everyone, welcome to the Golang tutorial series. In this post, you will learn and understand how to create custom errors in golang, which we can use in the functions and packages. The below example program was created to provide more details about how to deal with custom errors in go and also it is tested and shared in the same post.

What are Errors?
The errors are unexpected scenarios in an application. Let us consider, we have an application in which we would like to collect the employee’s information (i.e. Id, Name, Age and etc…) from the user and same should be stored into the database. So, what could go wrong during this process? The user may provide wrong or invalid data to the system, our application should be capable enough to handle these scenarios. Now, let`s see how to create a custom error with the below examples.
Creating an errors using errors.New() function
In order to create custom errors in golang, the easiest way is using the New() function from the errors package and you can get more details about errors.New() functions and it`s implementation here. Also, see the quick usage below.
errors.New("Your error message goes here!!!")
Complete Example
In the below example, we will have an add() function, which will take Employee type as an argument and the same function will throw custom errors if employee object has a wrong or invalid data for its attributes by using New(“your_error_message”) function from errors package.
package main import ( "errors" "fmt" ) type Employee struct { Id int Name string Age int } func main() { error := add(Employee{Id:-1, Name:"Dinesh Krishnan", Age:20}) if error != nil { fmt.Println(error) return } fmt.Println("Employee added successfully") } func add(employee Employee) error { if employee.Id < 0 { return errors.New("Invalid employee Id") } if employee.Name == "" { return errors.New("Invalid or empty employee name") } if employee.Age < 0 { return errors.New("Invalid employee age") } // do database operation here... return nil }
Run with Go Playground - https://play.golang.org/p/5huDaiYwlPc
Output
Invalid employee Id
References
- https://golang.org/doc/
- https://golang.org/pkg/
- https://golang.org/pkg/fmt/
- https://golang.org/pkg/fmt/#Println
- https://golang.org/pkg/errors/
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet