스위프트 에러 핸들링

강기환·2022년 11월 3일
post-thumbnail

1. 에러 타입 선언하기

Error 프로토콜을 따르는 열거형 선언

enum FileTransferError: Error {
	case noConnection
    case lowBandwidth
    case fileNotFound
}

2. 에러 던지기

func transferFile() throws -> Bool { }
let connectionOK = true
let connectionSpeed = 30.00
let fileFound = false

enum FileTransferError: Error {
	case noConnection
    case lowBandwidth
    case fileNotFound
}

func fileTransfer() throws {

	guard connectionOK else {
    	throw FileTransferError.noConnection
    }
    
    guard connectionSpeed > 30 else {
    	throw FileTransferError.lowBandwidth
    }
    
    guard fileFound else {
    	throw FileTransferError.fileNotFound
    }
}

메서드 내에 있는 각각의 guard 구문은 각 조건이 참인지 거짓인지를 검사한다. 만약 거짓이라면 throw 구문을 사용하여 FileTransferError 열거형에 있는 에러 값들 중 하나를 던진다.

do-catch 구문 사용

func sendFile() -> String {

	do {
    	try fileTransfer()
    } catch FileTransferError.noConnection {
    	return "No Network Connection"
    } catch FileTransferError.lowBandwidth {
    	return "File Transfer Speed too Low"
    } catch FileTransferError.fileNotFound {
    	return "File not Found"
    } catch {
    	return "Unknown error"
    }
    
    return "Successful transfer"
}

3. 에러 객체에 접근하기

do {
	try filemgr.createDirectory(atPath: newDir, withIntermediateDirectories: true, attributes: nil)
    } catch let error {
    	print("Error: \(error.localizedDescription)")
}

4. 에러 캐칭 비활성화하기

try! 구문을 사용하면 do-catch 구문 내에서 메서드가 호출되도록 감싸지 않아도 스로잉 메서드가 강제로 실행된다.

try! fileTransfer

5. defer 구문 사용하기

defer 구문은 메서드가 결과를 반환하기 직전에 실행되어야 하는 일련의 코드를 지정할 수 있게 해준다.

func sendFile() -> String {

	defer {
    	removeTmpFiles()
        closeConnection()
    }
    
	do {
    	try fileTransfer()
    } catch FileTransferError.noConnection {
    	return "No Network Connection"
    } catch FileTransferError.lowBandwidth {
    	return "File Transfer Speed too Low"
    } catch FileTransferError.fileNotFound {
    	return "File not Found"
    } catch {
    	return "Unknown error"
    }
    
    return "Successful transfer"
}
profile
백엔드개발자 꿈나무

0개의 댓글