반응형
이번 챕터에서는 에러 핸들링에 대해 알아보겠습니다.
비동기 이벤트를 다룰 때 에러가 항상 발생할 수 있습니다.
그래서 에러를 다루는 기술을 굉장히 중요합니다.
Publisher<Output, Failure>
Failure 이 친구에 집중해봅시다.
Never
publisher가 fail 이벤트가 절대 일어나지 않는 경우 사용합니다.
예를들어 Just를 확인해보면 Failure가 Never로 정의된 것을 볼 수 있습니다.
setFailureType
infallilbe publisher 를 만드는 방법!
assign(to:on:)
assign 이 걸려있는 곳에서 setFailureType을 하려고 하면 컴파일이 되지 않습니다.
Failure가 Never 일때만 assign이 가능한것으로 보입니다.
assertNoFailure
에러가 발생헀을 때 assert를 걸어서 개발자가 인지하게 만드는 방법입니다.
assert를 거는건 평소에도 많이 사용하는 방법입니다.
필수적으로 보장되어야 하는 값이 있다면 이것을 사용하면 유용할 듯 합니다.
Just("Hello")
.setFailureType(to: MyError.self)
.tryMap { _ in throw MyError.ohno }
.assertNoFailure()
.sink(receiveValue: { print("Got value: \($0)") })
.store(in: &subscriptions)
tryMap 부분에서 일부러 에러를 발생시키는 예제입니다.
에러를 만나면 아래와 같이 에러가 발생합니다.
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
Dealing with failure
try* operators
let names = ["Scott", "Marin", "Shai", "Florent"].publisher
names
.map { value in
let length = value.count
guard length >= 5 else {
throw NameError.tooShort(value)
}
return value.count
}
이런 식으로 코드를 작성했을 때, map 부분에서 컴파일 에러가 발생합니다.
Invalid conversion from throwing function of type '(String) throws -> _' to non-throwing function type '(String) -> T'
여기서 map -> tryMap 으로 변경하면 컴파일 에러가 사라집니다.
.tryMap { value -> Int in
let length = value.count
guard length >= 5 else {
throw NameError.tooShort(value)
}
return value.count
}
——— Example of: tryMap ———
Got value: 5
Got value: 5
Completed with failure(__lldb_expr_13.(unknown context at $10816a834).(unknown context at $10816a8d0).(unknown context at $10816a8d8).NameError.tooShort("Shai"))
Mapping errors
.tryMap { throw NameError.tooShort($0) }
반응형
'iOS > Combine' 카테고리의 다른 글
[Combine] Chapter 17: Schedulers (0) | 2021.02.03 |
---|---|
[Combine 책 정리] Chapter 13: Resource Management (0) | 2021.01.27 |
[Combine 책 정리] Chapter 12: Key-Value Observing (0) | 2021.01.27 |
[Combine 책 정리] Chapter 11: Timers (0) | 2021.01.27 |
[Combine 책 정리] Chapter 10: Debugging (0) | 2021.01.27 |