앞에서 작성한 코드에, 예외처리를 추가해보자.
만약, 해당 메서드를 호출하면서 name에 값을 안넣는다면?
필수 파라미터가 없는 경우 Go에서 예외처리를 해보자.

 

1.  greetings/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
}
  • 코드 변경으로 인해 Hello function은 두가지 종류의 return 값이 있다. String 또는 Error 만약 값이 없거나 유효하지 않은 값일 경우 Error가 반환된다.
  • 기존코드에 errors 패키지를 추가했다.
  • return 값에 nil(오류없음) 을 추가 함으로써 호출한 곳에서 함수가 성공적으로 실행됬음을 알 수 있다.

2. hello/hello.go 파일로 이동해서, error 값이 리턴됬을 경우 처리하는 로직을 추가한다.
아래 코드로 수정해보자.

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)
}
  • timestamp 혹은 소스파일 정보 없이 로그 메세지 시작부분에 "greetings : " 를 표시하도록  prefix를 설정한다.
  • 오류를 포함한 모든 값을 변수에 할당한다.
  • Hello의 값을 "" 빈값으로 설정함으로써 에러처리가 정상적으로 되는지 확인해본다.
  • 로그 패키지에 있는 Fatal function을 사용해서 에러가 있는 경우 log를 찍고 프로그램을 종료하도록 한다.

 

 

 

3. 코드를 구성했다면, hello 폴더로 이동해서 hello 파일을 실행해본다.

정상적으로 에러처리가 된 것을 확인할 수 있다!

+ Recent posts