← Back to Go Course | Chapter 9: Error Handling | Lesson 2 of 6

अपने Custom Error Types

एक custom error type अतिरिक्त fields के साथ अपना खुद का error form design करने जैसा है, ताकि इसे पाने वाला code सिर्फ एक message से ज़्यादा पढ़ सके -- यह बिल्कुल जांच सके कि कौन सी problem हुई।
Syntax
go
type NameError struct {
    Field type
}

func (e *NameError) Error() string {
    return "message"
}

Defining a Custom Error Type

एक custom error बस एक Error() string method वाला struct है, जो इसे सिर्फ एक साधारण message से आगे अतिरिक्त structured fields रखने देता है -- तब उपयोगी जब calling code को सिर्फ text से ज़्यादा context चाहिए।

उदाहरण: Defining a Custom Error Type

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define a struct type named ValidationError
type ValidationError struct {
	Field string
	Msg   string
}

// Define the method Error on type ValidationError
func (e *ValidationError) Error() string {
	// Sprintf builds a formatted string instead of printing it
	return fmt.Sprintf("%s: %s", e.Field, e.Msg)
}

// main is where the program starts running
func main() {
	var err error = &ValidationError{Field: "age", Msg: "must be positive"}
	// Print the values followed by a newline
	fmt.Println(err)
}

Returning a Custom Error

कोई function standard error interface के ज़रिए एक custom error type return कर सकता है, इसलिए सिर्फ fail हुआ या नहीं इसकी परवाह करने वाला calling code इसे किसी भी दूसरे error जैसा treat कर सकता है, जबकि details चाहने वाला code इसे आगे inspect कर सकता है।

उदाहरण: Returning a Custom Error

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define a struct type named OutOfStockError
type OutOfStockError struct {
	Item string
}

// Define the method Error on type OutOfStockError
func (e *OutOfStockError) Error() string {
	// Sprintf builds a formatted string instead of printing it
	return fmt.Sprintf("%s is out of stock", e.Item)
}

// Define the function checkStock
func checkStock(item string, qty int) error {
	// Check whether qty <= 0
	if qty <= 0 {
		// Send &OutOfStockError{Item: item} back to the caller
		return &OutOfStockError{Item: item}
	}
	return nil
}

func main() {
	if err := checkStock("widget", 0); err != nil {
		fmt.Println(err)
	}
}

Extracting a Custom Error with errors.As

errors.As जांचता है कि कोई error (या वह जो भी wrap करता है) किसी specific custom error type से मेल खाती है या नहीं, और अगर हां, एक target variable को इससे populate करता है -- calling code को सिर्फ एक message string नहीं बल्कि structured fields पर react करने देते हुए।

Note: errors.As किसी matching type को ढूंढने के लिए wrapped errors की किसी भी chain को भी unwrap करता है।

उदाहरण: Extracting a Custom Error with errors.As

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"errors"
	"fmt"
)

// Define a struct type named OutOfStockError
type OutOfStockError struct {
	Item string
}

// Define the method Error on type OutOfStockError
func (e *OutOfStockError) Error() string {
	// Sprintf builds a formatted string instead of printing it
	return fmt.Sprintf("%s is out of stock", e.Item)
}

// main is where the program starts running
func main() {
	var err error = &OutOfStockError{Item: "widget"}

	// Declare oosErr with the zero value of its type
	var oosErr *OutOfStockError
	// Check whether errors.As(err, &oosErr)
	if errors.As(err, &oosErr) {
		fmt.Println("out of stock item:", oosErr.Item)
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक custom error struct define करना लेकिन इस पर Error() string implement करना भूल जाना, इसलिए यह असल में error interface को satisfy नहीं करता।
  2. Error() के लिए एक value receiver उपयोग करना लेकिन कहीं और असंगत रूप से &MyError{} (एक pointer) return करना, type assertion mismatches का कारण बनते हुए।
  3. किसी custom error type में सिर्फ एक string message store करना जब structured fields (जैसे एक status code) callers को programmatically react करने देते।
चैप्टर सारांश
  • एक custom error type कोई भी struct है जो Error() string method implement करता है।
  • Custom errors एक साधारण message से आगे structured data रख सकते हैं, जैसे एक error code या invalid value।
  • Callers एक specific custom error type जांचने और निकालने के लिए errors.As उपयोग करते हैं।
  • Custom errors failure handling को error message strings parse करने से ज़्यादा सटीक बनाते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.