본문 바로가기
Language/Go

Go - Return 과 handle an error

by ocwokocw 2021. 11. 28.

참조: https://go.dev/doc/tutorial/handle-errors

개요

error 를 다루는것은 견고한 코드를 작성하는데 있어 필수요소라고 할 수 있다. 이번에는 greetings 모듈에서 error 를 반환해보고 caller 에서 이를 다루어보도록 한다.

- error 반환

인사할 사람이 없다면 답장을 보내도 의미가 없다. 호출자가 이름을 빈값으로 호출했다면 caller 에게 error 를 반환해보도록 하자. greetings.go 파일을 아래와 같이 수정한다.
 
package greetings

import (
    "errors"
    "fmt"
)

// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
    // If no name was given, return an error with a message.
    if name == "" {
        return "", errors.New("empty name")
    }

    // If a name was received, return a value that embeds the name
    // in a greeting message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message, nil
}
 
 
위에 코드는 아래와 같은 의미를 갖는다.
  • 함수에서 2 개의 값(string, error)을 반환하였다. Go 에서는 하나의 함수에서 여러 개의 값을 반환할 수 있다. caller 가 2번째 값을 체크하면 error 가 발생했는지 알 수 있다.
  • Go 의 standard library 인 errors package 를 import 하여 errors.New 를 사용할 수 있도록 했다.
  • 유효한 요청인지 체크하기 위해 if 문을 추가하여 유효하지 않으면 error 를 반환했다.
  • 성공적인 메시지를 반환할 때 2 번째 값으로 nil 을 추가했다. 이렇게 하면 caller 가 Hello 함수를 호출하여 2 번째 값으로 nil 을 반환받았을때 해당 함수가 성공적으로 수행되었음을 알 수 있다.

- error 반환 함수 호출

hello.go 에서 위에서 만든 함수를 호출해보자. 아래 코드를 복사한다.
 
package main

import (
    "fmt"
    "log"

    "example.com/greetings"
)

func main() {
    // Set properties of the predefined Logger, including
    // the log entry prefix and a flag to disable printing
    // the time, source file, and line number.
    log.SetPrefix("greetings: ")
    log.SetFlags(0)

    // Request a greeting message.
    message, err := greetings.Hello("")
    // If an error was returned, print it to the console and
    // exit the program.
    if err != nil {
        log.Fatal(err)
    }

    // If no error was returned, print the returned message
    // to the console.
    fmt.Println(message)
}
 
 
위의 코드의 의미는 아래와 같다.
  • log message 의 시작부분에서 ("greetings: ") 를 출력할 수 있도록 log package 를 설정했다. timestamp 나 source file 의 정보 없이 간단하게 출력하였다.
  • Hello 함수를 호출하고 error 를 포함한 반환값을 할당했다.
  • err 가 nil 이 아닐때에는 코드가 계속 수행되는 의미가 없다.
  • error 정보를 출력하시 위해 standard library 인 log package 함수를 사용했다. 만약 error 가 발생하면 log package 의 Fatal 함수를 사용하여 error 를 출력하고 프로그램을 중단한다.
hello directory 에서 go run . 을 실행하면 아래와 같이 에러가 발생한다.
 
go run .
greetings: empty name
exit status 1

'Language > Go' 카테고리의 다른 글

Go - test  (0) 2021.11.28
Go - multiple input 과 return  (0) 2021.11.28
Go - random 과 slice  (0) 2021.11.28
Go - called module 과 caller module  (0) 2021.11.28
Go - hello world 와 external package  (0) 2021.11.28

댓글