The Error Interface in Go

List Topics
February 18, 2025
No Comments
6 min read

In Go, error handling is an essential part of writing robust programs. Unlike many programming languages that use exceptions, Go uses a more explicit approach by using the error type to represent errors.

The error type in Go is actually an interface, which means it defines a set of methods that types must implement in order to be considered an error. This approach allows for flexibility and simplicity in handling errors.

1️⃣ The error Interface

The error interface in Go is defined as:

Go
type error interface {
    Error() string
}

This interface has a single method, Error(), which returns a string that describes the error.

How it works:

  • Any type that implements the Error() method (i.e., a method that returns a string) is considered to be of type error.
  • You can create custom error types by defining a new struct and implementing the Error() method for that type.

Example of the error interface in action:

Go
package main

import (
    "fmt"
)

type MyError struct {
    Code    int
    Message string
}

// Implement 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: "Not Found"}
    if err != nil {
        fmt.Println(err.Error()) // Calls the Error method
    }
}

🔹 Output:

Bash
Error code: 404, Message: Not Found

👉 In this example, we created a custom error type MyError with Code and Message fields. We then implemented the Error() method for MyError, making it compatible with the error interface.

2️⃣ Built-in Errors

Go provides a built-in error type that can be used to represent errors without needing to create custom types. You can use the errors.New() function to create a basic error.

Example:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("Something went wrong!")
    if err != nil {
        fmt.Println(err) // Prints the error message
    }
}

🔹 Output:

Bash
Something went wrong!

👉 In this case, we used errors.New() to create a simple error with a string message.

3️⃣ Wrapping Errors

Go 1.13 introduced error wrapping, which allows you to add additional context to errors. You can use fmt.Errorf() to wrap an error with more information.

Example:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("database connection failed")
    wrappedErr := fmt.Errorf("could not connect to the database: %w", err)

    fmt.Println(wrappedErr) // Prints the wrapped error message
}

🔹 Output:

Bash
could not connect to the database: database connection failed

👉 The %w verb in fmt.Errorf() is used to wrap an existing error, which can later be unwrapped if needed to get the original error.

4️⃣ Unwrapping Errors

You can use errors.Unwrap() to retrieve the original error from a wrapped error.

Example:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("database connection failed")
    wrappedErr := fmt.Errorf("could not connect to the database: %w", err)

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

🔹 Output:

Bash
Unwrapped Error: database connection failed

👉 By using errors.Unwrap(), we can extract the original error that was wrapped.

5️⃣ Custom Error Types with Error() Method

Creating custom error types allows for more control over the error information, such as adding more context or attaching additional metadata.

Example:

Go
package main

import (
    "fmt"
)

type FileNotFoundError struct {
    FileName string
}

func (e *FileNotFoundError) Error() string {
    return fmt.Sprintf("File '%s' not found", e.FileName)
}

func main() {
    err := &FileNotFoundError{FileName: "config.json"}
    fmt.Println(err.Error()) // Calls the Error method of the custom error type
}

🔹 Output:

Bash
File 'config.json' not found

👉 In this example, FileNotFoundError is a custom error type, and we implemented the Error() method to provide a custom error message.

Summary:

  • In Go, errors are represented by the error interface, which has a single method, Error() string.
  • Any type that implements the Error() method can be considered an error.
  • You can create custom error types by defining a struct and implementing the Error() method.
  • The built-in errors.New() function allows for creating simple errors with string messages.
  • Go 1.13 introduced error wrapping with fmt.Errorf() and unwrapping with errors.Unwrap() for adding context to errors.

Error handling in Go is explicit and requires developers to manage errors actively, which leads to clearer and more reliable code.


Error Handling in Go: The Error Interface

Go-তে ত্রুটি (error) হ্যান্ডলিং একটি গুরুত্বপূর্ণ অংশ। অনেক প্রোগ্রামিং ভাষার মতো যেখানে exceptions ব্যবহার করা হয়, Go তে ত্রুটি পরিচালনার জন্য error টাইপ ব্যবহার করা হয়, যা একটি ইন্টারফেস হিসেবে কাজ করে।

Go-তে error টাইপটি একটি ইন্টারফেস, যার মানে এটি একটি সেট মেথড ডিফাইন করে, যেগুলি টাইপগুলোকে ত্রুটি হিসাবে গণ্য করতে হবে। এই পদ্ধতি Go-কে একটি নমনীয় এবং সহজ উপায়ে ত্রুটি হ্যান্ডল করতে সক্ষম করে।

1️⃣ The error Interface

Go-তে error ইন্টারফেসটি এইভাবে ডিফাইন করা হয়:

Go
type error interface {
    Error() string
}

এই ইন্টারফেসের একটি মাত্র মেথড রয়েছে, Error(), যা ত্রুটির বর্ণনা করা একটি স্ট্রিং রিটার্ন করে।

কিভাবে কাজ করে:

  • যেকোনো টাইপ যেটি Error() মেথড (যেটি একটি স্ট্রিং রিটার্ন করে) বাস্তবায়ন করে, তাকে error টাইপ হিসেবে বিবেচনা করা হয়।
  • আপনি কাস্টম ত্রুটি টাইপ তৈরি করতে পারেন একটি নতুন struct ডিফাইন করে এবং সেই struct এর জন্য Error() মেথড বাস্তবায়ন করে।

error ইন্টারফেসের ব্যবহার উদাহরণ:

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: "Not Found"}
    if err != nil {
        fmt.Println(err.Error()) // Error মেথড কল করা
    }
}

🔹 Output:

Bash
Error code: 404, Message: Not Found

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

2️⃣ Built-in Errors

Go-তে বিল্ট-ইন ত্রুটি টাইপও রয়েছে, যেগুলি আপনাকে ত্রুটি তৈরি করতে সহায়তা করে, যাতে কাস্টম টাইপ তৈরি করার প্রয়োজন না পড়ে। আপনি errors.New() ফাংশন ব্যবহার করে একটি সাধারণ ত্রুটি তৈরি করতে পারেন।

উদাহরণ:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("Something went wrong!")
    if err != nil {
        fmt.Println(err) // ত্রুটির বার্তা মুদ্রণ করা
    }
}

🔹 Output:

Bash
Something went wrong!

👉 এখানে, আমরা errors.New() ব্যবহার করেছি একটি সাধারণ ত্রুটি তৈরি করার জন্য, যেখানে একটি স্ট্রিং বার্তা রয়েছে।

3️⃣ Wrapping Errors

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

উদাহরণ:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("database connection failed")
    wrappedErr := fmt.Errorf("could not connect to the database: %w", err)

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

🔹 Output:

Bash
could not connect to the database: database connection failed

👉 এখানে, %w ভার্বটি fmt.Errorf() তে ব্যবহার করা হয়েছে, যা একটি বিদ্যমান ত্রুটিকে মোড়ক (wrap) করে, এবং পরে আপনি এই ত্রুটিটিকে আনর্যাপ (unwrap) করতে পারেন।

4️⃣ Unwrapping Errors

আপনি errors.Unwrap() ব্যবহার করে মোড়ক (wrapped) ত্রুটি থেকে মূল ত্রুটিটি পুনরুদ্ধার (unwrap) করতে পারেন।

উদাহরণ:

Go
package main

import (
    "fmt"
    "errors"
)

func main() {
    err := errors.New("database connection failed")
    wrappedErr := fmt.Errorf("could not connect to the database: %w", err)

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

🔹 Output:

Bash
Unwrapped Error: database connection failed

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

5️⃣ Custom Error Types with Error() Method

কাস্টম ত্রুটি টাইপ তৈরি করা আরও নিয়ন্ত্রণ দেয় ত্রুটির তথ্যের উপর, যেমন অতিরিক্ত কনটেক্সট যোগ করা বা অতিরিক্ত মেটাডেটা সংযুক্ত করা।

উদাহরণ:

Go
package main

import (
    "fmt"
)

type FileNotFoundError struct {
    FileName string
}

func (e *FileNotFoundError) Error() string {
    return fmt.Sprintf("File '%s' not found", e.FileName)
}

func main() {
    err := &FileNotFoundError{FileName: "config.json"}
    fmt.Println(err.Error()) // কাস্টম ত্রুটি টাইপের Error মেথড কল করা
}

🔹 Output:

Bash
File 'config.json' not found

👉 এখানে, FileNotFoundError একটি কাস্টম ত্রুটি টাইপ, এবং আমরা Error() মেথড বাস্তবায়ন করেছি যাতে একটি কাস্টম ত্রুটি বার্তা প্রদান করা যায়।

সারসংক্ষেপ:

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

Go-তে ত্রুটি হ্যান্ডলিং খুব স্পষ্ট এবং প্রোগ্রামারদেরকে ত্রুটির সাথে সক্রিয়ভাবে কাজ করতে উৎসাহিত করে, যা কোডকে পরিষ্কার এবং নির্ভরযোগ্য করে তোলে।

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