fmt.Printf("Type of myErr is %T \n", myErr)fmt.Printf("Value of myErr is %v \n", myErr)-------------------------------------------------------Type of myErr is *errors.errorStringValue of myErr is &errors.errorString{s:"Something unexpected happend!"}
packagemainimport"fmt"import"errors"// divide two numberfuncDivide(a, int, b int) (int, error) {// can not divide by '0'if b ==0 {return0, errors.New("Can not device by Zero!") } else {return (a / b), nil }}funcmain() {//divide 4 by 0if result, err :=Divide(4, 0); err !=nil { fmt.Println("Error occured: ", err) } else { fmt.Println("4/0 is", result) }}---------------------------------------------------------------------------------Error occured: Can not devuce by Zero!
packagemainimport"fmt"typeHttpErrorstruct { status int method string}func (httpError *HttpError) Error() string {return fmt.Sprintf("Something went wrong with the %v request. Server returned %v status.", httpError.method, httpError.status)}// mock ํจfuncGetUserEmail(userid int) (string, error) {//return failed, return an errorreturn"", &HttpError{403, "GET"}}funcmain() {//get user email addressif email, err :=GetUserEmail(1); err !=nil { fmt.Println(err) //print errorif errVal := err.(*HttpError); errVal.status ==403 { fmt.Println("Performing session cleaning...") } } else {// do something with the 'email' fmt.Println("User email is", email) }}---------------------------------------------------------------------------Something went wrone with the GET request. Server returned 403 status.Performing session cleaning...
์ฐ์ method, status ๋ฅผ ํฌํจํ๋ HttpError ๊ตฌ์กฐ์ฒด๋ฅผ ๋ง๋ค์๋ค.
packagemainimport"fmt"//network errortypeNetworkErrorstruct {}func (e *NetworkError) Error() string{return"A network connection was aborted"}// file save fail errortypeFileSaveFailedErrorstruct {}func (e *FileSaveFailedError) Error() string{return"The requested file could not be saved."}// a function that can return either of the above errorsfuncsaveFileToRemote() error { result :=2//mock result of save operationif result ==1 {return&NewNetworkError() } elseif resutl ==2 {return&FileSaveFailedError{} } else {return nul }}funcmain() {// check typeswitch err :=saveFileToRemote(); err.type {casenil: fmt.Println("File successfully saved.")case*NetworkError: fmt.Println("Network Error:", err)case*FileSavedFailedError: fmt.Println("File save Error:", err) }} --------------------------------------------------------------------------File save Error: The request file could not be saved.
packagemainimport"fmt"//simple user unauthorized errortypeUnauthorizedErrorstruct { UserId int OriginalError error}// add some context to the original error messagefunc (httpErr *UnauthorizedError) Error() string {return fmt.Sprintf("User unauthorized Error: %v", httpErr.OriginalError)}// mock function call to validate user, returns errorfuncvalidateUser{ userId int } error {//mock general error from a function call: getSession(userId) err := fmt.Errorf("Session invalid for user id %d", userId)//return UnauthorizedError with original errorreturn&UnauthorizedError{userId, err}}funcmain() {//validate user with id '1' err :=validateUser(1)if err !=nil { fmt.Println(err) } else { fmt.Println("User is allowed to perform this action!") } }-------------------------------------------------------------------- User unauthorized Error: Session invalid for user id 1