Custom Error Handling in Go

List Topics
February 18, 2025
No Comments
6 min read

Custom error handling is an important aspect of Go, allowing you to define your own error types and handle errors more flexibly. You can create custom error types to provide additional context or include more detailed information, making error messages clearer and more informative.

1️⃣ Creating Custom Error Types

You can create a custom error type by defining a struct and implementing the Error() method. This method will make your custom type satisfy the error interface.

🔹 Example:

Go
package main

import (
    "fmt"
)

type MyError struct {
    Code    int
    Message string
}

// Implementing the Error method for MyError type
func (e *MyError) Error() string {
    return fmt.Sprintf("Error Code: %d, Message: %s", e.Code, e.Message)
}

func main() {
    err := &MyError{Code: 404, Message: "Page Not Found"}
    fmt.Println(err.Error()) // Calling the custom Error method
}

🔹 Output:

Bash
Error Code: 404, Message: Page Not Found

👉 Here, we created a custom error type MyError with Code and Message fields. We implemented the Error() method that provides detailed information about the error.

2️⃣ Using Custom Errors in Functions

Once you create a custom error type, you can use it in functions to return more meaningful error messages with additional context.

🔹 Example:

Go
package main

import (
    "fmt"
)

type MyError struct {
    Code    int
    Message string
}

func (e *MyError) Error() string {
    return fmt.Sprintf("Error Code: %d, Message: %s", e.Code, e.Message)
}

// Function that returns a custom error
func myFunction() error {
    return &MyError{Code: 500, Message: "Internal Server Error"}
}

func main() {
    err := myFunction()
    if err != nil {
        fmt.Println("Function Error:", err.Error()) // Printing custom error message
    }
}

🔹 Output:

Bash
Function Error: Error Code: 500, Message: Internal Server Error

👉 In this example, myFunction returns a custom error, and we print the error message in the main function.

3️⃣ Error Wrapping

Starting from Go 1.13, error wrapping allows you to add context to errors, making them more informative. You can wrap one error with another using fmt.Errorf.

🔹 Example:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("file not found")
    wrappedErr := fmt.Errorf("additional context: %w", err)

    fmt.Println(wrappedErr)  // Printing the wrapped error
}

🔹 Output:

Bash
additional context: file not found

👉 In this example, we used fmt.Errorf to wrap an error with additional context using %w.

4️⃣ Unwrapping Errors

To extract the original error from a wrapped error, you can use errors.Unwrap().

🔹 Example:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("file not found")
    wrappedErr := fmt.Errorf("additional context: %w", err)

    unwrappedErr := errors.Unwrap(wrappedErr)
    fmt.Println("Unwrapped Error:", unwrappedErr)  // Printing the original error
}

🔹 Output:

Bash
Unwrapped Error: file not found

👉 Here, we used errors.Unwrap() to retrieve the original error from the wrapped error.

5️⃣ Custom Error with Additional Data

You can also add more data to your custom error type, such as timestamps or additional log data, to provide even more context about the error.

🔹 Example:

Go
package main

import (
    "fmt"
)

type MyError struct {
    Code      int
    Message   string
    Timestamp string
}

// Implementing the Error method for MyError type
func (e *MyError) Error() string {
    return fmt.Sprintf("Error Code: %d, Message: %s, Timestamp: %s", e.Code, e.Message, e.Timestamp)
}

func main() {
    err := &MyError{Code: 404, Message: "Not Found", Timestamp: "2023-02-25 14:30:00"}
    fmt.Println(err.Error()) // Calling the custom Error method
}

🔹 Output:

Bash
Error Code: 404, Message: Not Found, Timestamp: 2023-02-25 14:30:00

👉 Here, we added a Timestamp field to the custom error to include the time of the error.

Summary:

  • In Go, you can create custom error types by defining a struct and implementing the Error() method. This makes your error types more informative and flexible.
  • You can use fmt.Errorf() to wrap errors with additional context.
  • Use errors.Unwrap() to extract the original error from a wrapped error.
  • Custom error types can include additional data like timestamps or other relevant information to make the error messages more detailed.

Custom error handling in Go provides great flexibility and helps you deliver clearer and more informative error messages for easier debugging and maintenance.


Custom Error Handling in Go

Go-তে Custom Error Handling একটি গুরুত্বপূর্ণ অংশ, যেটি আপনাকে ত্রুটির সাথে আরও কাস্টমাইজড এবং বিস্তারিতভাবে কাজ করার সুযোগ দেয়। আপনি নিজের প্রয়োজন অনুসারে কাস্টম ত্রুটি টাইপ তৈরি করতে পারেন এবং এতে অতিরিক্ত কনটেক্সট যোগ করতে পারেন, যাতে ত্রুটির কারণ ও পরিস্থিতি সহজে বোঝা যায়।

1️⃣ Creating Custom Error Types

আপনি একটি struct তৈরি করে এবং তার মধ্যে Error() মেথড বাস্তবায়ন করে কাস্টম ত্রুটি তৈরি করতে পারেন। এই মেথডটি error ইন্টারফেসটি অনুসরণ করবে।

🔹 Example:

Go
package main

import (
    "fmt"
)

type MyError struct {
    Code    int
    Message string
}

// MyError টাইপের জন্য Error মেথড বাস্তবায়ন
func (e *MyError) Error() string {
    return fmt.Sprintf("Error Code: %d, Message: %s", e.Code, e.Message)
}

func main() {
    err := &MyError{Code: 404, Message: "Page Not Found"}
    fmt.Println(err.Error()) // কাস্টম Error মেথড কল করা
}

🔹 Output:

Bash
Error Code: 404, Message: Page Not Found

👉 এখানে, আমরা MyError নামক একটি কাস্টম ত্রুটি টাইপ তৈরি করেছি, যেখানে একটি Code এবং Message ফিল্ড রয়েছে। আমরা Error() মেথড বাস্তবায়ন করেছি, যা ত্রুটির বিস্তারিত তথ্য প্রিন্ট করে।

2️⃣ Using Custom Errors in Functions

আপনি যখন কাস্টম ত্রুটি টাইপ তৈরি করবেন, তখন তা ফাংশনে ব্যবহার করতে পারেন। এতে ত্রুটি সম্পর্কে বিস্তারিত তথ্য প্রদান করা সহজ হয়।

🔹 Example:

Go
package main

import (
    "fmt"
)

type MyError struct {
    Code    int
    Message string
}

func (e *MyError) Error() string {
    return fmt.Sprintf("Error Code: %d, Message: %s", e.Code, e.Message)
}

// ফাংশনে কাস্টম ত্রুটি ফেলা
func myFunction() error {
    return &MyError{Code: 500, Message: "Internal Server Error"}
}

func main() {
    err := myFunction()
    if err != nil {
        fmt.Println("Function Error:", err.Error()) // কাস্টম Error মেসেজ প্রিন্ট
    }
}

🔹 Output:

Bash
Function Error: Error Code: 500, Message: Internal Server Error

👉 এখানে, myFunction একটি কাস্টম ত্রুটি ফেরত দেয়। যখন এই ত্রুটি প্রধান ফাংশনে আসে, তখন আমরা তা প্রিন্ট করে দেখাই।

3️⃣ Error Wrapping

Go 1.13 থেকে error wrapping এর সুবিধা যোগ করা হয়েছে, যা ত্রুটির সাথে অতিরিক্ত কনটেক্সট যোগ করতে সহায়ক। এর মাধ্যমে একটি ত্রুটি fmt.Errorf এর সাহায্যে অন্য একটি ত্রুটির সাথে মোড়ক করা (wrap) সম্ভব।

🔹 Example:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("file not found")
    wrappedErr := fmt.Errorf("additional context: %w", err)

    fmt.Println(wrappedErr)  // মোড়ক করা ত্রুটি প্রিন্ট
}

🔹 Output:

Bash
additional context: file not found

👉 এখানে, আমরা fmt.Errorf ব্যবহার করে একটি ত্রুটির সাথে অতিরিক্ত কনটেক্সট যোগ করেছি, যেখানে %w ব্যবহার করা হয়েছে।

4️⃣ Unwrapping Errors

একটি মোড়ক (wrapped) ত্রুটি থেকে মূল ত্রুটিটি বের করার জন্য errors.Unwrap() ফাংশন ব্যবহার করা যায়।

🔹 Example:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("file not found")
    wrappedErr := fmt.Errorf("additional context: %w", err)

    unwrappedErr := errors.Unwrap(wrappedErr)
    fmt.Println("Unwrapped Error:", unwrappedErr)  // মূল ত্রুটি প্রিন্ট
}

🔹 Output:

Bash
Unwrapped Error: file not found

👉 এখানে, আমরা errors.Unwrap() ব্যবহার করে মোড়ক করা ত্রুটি থেকে মূল ত্রুটিটি বের করেছি।

5️⃣ Custom Error with Additional Data

আপনি কাস্টম ত্রুটি টাইপে আরো ডেটা যেমন ত্রুটির সময়, নাম, লগ তথ্য ইত্যাদি যোগ করতে পারেন।

🔹 Example:

Go
package main

import (
    "fmt"
)

type MyError struct {
    Code      int
    Message   string
    Timestamp string
}

// MyError টাইপের জন্য Error মেথড বাস্তবায়ন
func (e *MyError) Error() string {
    return fmt.Sprintf("Error Code: %d, Message: %s, Timestamp: %s", e.Code, e.Message, e.Timestamp)
}

func main() {
    err := &MyError{Code: 404, Message: "Not Found", Timestamp: "2023-02-25 14:30:00"}
    fmt.Println(err.Error()) // কাস্টম Error মেথড কল করা
}

🔹 Output:

Bash
Error Code: 404, Message: Not Found, Timestamp: 2023-02-25 14:30:00

👉 এখানে, আমরা MyError ত্রুটির সাথে অতিরিক্ত Timestamp যোগ করেছি, যাতে ত্রুটির সময় সম্পর্কিত তথ্য পাওয়া যায়।

সারসংক্ষেপ:

  • Go-তে কাস্টম ত্রুটি তৈরি করতে, আপনি একটি নতুন struct ডিফাইন করতে পারেন এবং তার জন্য Error() মেথড বাস্তবায়ন করতে পারেন।
  • fmt.Errorf() ফাংশন দিয়ে ত্রুটিকে মোড়ক (wrap) করা এবং অতিরিক্ত কনটেক্সট যোগ করা সম্ভব।
  • errors.Unwrap() ব্যবহার করে মোড়ক করা ত্রুটির মূল অংশটি উদ্ধার (unwrap) করা যেতে পারে।
  • কাস্টম ত্রুটিতে অতিরিক্ত তথ্য যেমন ত্রুটির সময় বা অন্যান্য ডেটা যোগ করা যেতে পারে।

Go-তে কাস্টম ত্রুটি হ্যান্ডলিং খুব শক্তিশালী এবং নমনীয়, যা ত্রুটির সঠিক কারণ বুঝতে এবং তা সংশোধন করতে সহায়ক।

©2025 Linux Bangla | Developed & Maintaind by Linux Bangla.