Swift Error Handling

  • Swift는 Error 프로토콜을 통해 error handling을 네이티브하게 지원한다.

Error enum

  • 다음과 같이 Error 프로토콜을 채택해 간단하게 Error enum을 만들 수 있게 해준다.
enum ValidationError: Error {
    case tooShort
    case tooLong
    case invalidCharacterFound(Character)
}

throws & throw

  • throws와 throw를 이용해 다음과 같이 위에서 만든 Error enum을 사용할 수 있다.
// throws function으로 만들고
func validate(username: String) throws {
    guard username.count > 3 else {
        // error 타입을 throw 한다
        throw ValidationError.tooShort
    }

    guard username.count < 15 else {
        // error 타입을 throw 한다    
        throw ValidationError.tooLong
    }

    for character in username {
        guard character.isLetter else {
            // error 타입을 throw 한다            
            throw ValidationError.invalidCharacterFound(character)
        }
    }
}

try 키워드

  • throws 함수를 호출 할 때는 try 키워드를 사용해야 한다.
  • try 키워드는 throw된 error를 handle 해준다.
func userDidPickName(_ username: String) {
    do {
        try validate(username: username)
        
        // validate에 성공했을 때
        submit(username)
    } catch {
        // validate에 실패했을 때
        // error 변수는 catch문 내에 자동으로 생성된다
        errorLabel.text = error.localizedDescription
    }
}
  • 위 코드를 실행시켜 validate에 실패하면 다음과 같이 error 문구를 나타낼 것이다.
The operation couldn’t be completed. (App.ValidationError error 0.)
  • 조금 더 명확하게 error를 구분하기 위해 아래와 같이 할 수 있다.

LocalizedError

  • LocalizedError를 채택해 다음과 같이 ValidationError를 확장한다.
  • errorDescription 프로퍼티를 implement해서 원하는 에러 메시지를 구현할 수 있다.
extension ValidationError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .tooShort:
            return NSLocalizedString(
                "Your username needs to be at least 4 characters long",
                comment: ""
            )
        case .tooLong:
            return NSLocalizedString(
                "Your username can't be longer than 14 characters",
                comment: ""
            )
        case .invalidCharacterFound(let character):
            let format = NSLocalizedString(
                "Your username can't contain the character '%@'",
                comment: ""
            )

            return String(format: format, String(character))
        }
    }
}
  • 그러면 이제 아래와 같이 무엇이 error인지 더 자세히 알려줄것이다.
Your username can't contain the character '-'

참고