Go Wrap Error 예시

개요[ | ]

Go Wrap Error 예시
package main

import (
	"fmt"
)

type MyHTTPError struct {
	Code int
}

func (e *MyHTTPError) Error() string {
	return fmt.Sprintf("HTTP Not Successful; code=%v", e.Code)
}

func (e *MyHTTPError) GetCode() int {
	return e.Code
}

func helloHTTPCode(code int) (string, error) {
	digit := code / 100
	if digit == 2 {
		return "Successful", nil
	}
	return "Not Successful", &MyHTTPError{Code: code}
}

func testHelloHTTPCode(code int) {
	result, err := helloHTTPCode(code)
	if e, ok := err.(*MyHTTPError); ok {
		fmt.Printf("result=[%s], err=[%s], code=[%d]\n", result, err, e.GetCode())
		return
	}
	fmt.Printf("result=[%s], err=[%s]\n", result, err)
}

func main() {
	testHelloHTTPCode(200) // result=[Successful], err=[%!s(<nil>)]
	testHelloHTTPCode(404) // result=[Not Successful], err=[HTTP Not Successful; code=404], code=[404]
	testHelloHTTPCode(409) // result=[Not Successful], err=[HTTP Not Successful; code=409], code=[409]
	testHelloHTTPCode(500) // result=[Not Successful], err=[HTTP Not Successful; code=500], code=[500]
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}