0
0
Goprogramming~30 mins

Custom error types in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom error types
📖 Scenario: You are building a simple program that processes orders. Sometimes, orders can have errors like invalid IDs or negative quantities. To handle these clearly, you want to create your own error types.
🎯 Goal: Learn how to create custom error types in Go and use them to return meaningful error messages.
📋 What You'll Learn
Create a custom error type struct
Implement the Error() method for the custom error type
Use the custom error type in a function to return errors
Print the error message from the custom error
💡 Why This Matters
🌍 Real World
Custom error types help you give clear, specific error messages in programs that handle many different error situations.
💼 Career
Understanding custom errors is important for writing clean, maintainable Go code in professional software development.
Progress0 / 4 steps
1
Create a custom error type struct
Create a struct called OrderError with two fields: OrderID of type int and Message of type string.
Go
Hint

Think of OrderError as a box holding the order number and a message explaining the error.

2
Implement the Error() method
Add a method called Error() to the OrderError struct that returns a string. It should return a formatted string like "Order {OrderID}: {Message}" using fmt.Sprintf.
Go
Hint

The Error() method lets Go treat your struct like a normal error with a message.

3
Use the custom error type in a function
Write a function called ProcessOrder that takes an orderID int and quantity int. If quantity is less than 1, return an OrderError with OrderID set to orderID and Message set to "invalid quantity". Otherwise, return nil.
Go
Hint

This function checks if the quantity is valid and returns your custom error if not.

4
Print the error message
Call ProcessOrder with orderID 101 and quantity 0. If it returns an error, print the error using fmt.Println.
Go
Hint

Use fmt.Println(err) to show the error message from your custom error.