
error.response?.status는 다음과 같이 동작:
// Optional Chaining 사용
error.response?.status
// 위 코드는 아래와 같은 의미
error.response !== null && error.response !== undefined
? error.response.status
: undefined
// Optional Chaining 없이 작성하면
if (error.response && error.response.status === 401) {
// ...
}
// Optional Chaining 사용
if (error.response?.status === 401) {
// ...
}
error.response가 null 또는 undefined일 때:
Cannot read property 'status' of undefined 에러 발생undefined 반환하고 에러 없이 진행// API 응답 처리
const userName = apiResponse?.data?.user?.name ?? 'Guest'
// 이벤트 핸들러
button?.addEventListener('click', handleClick)
// 배열 접근
const firstItem = items?.[0]
// 함수 호출
onSuccess?.() // onSuccess가 존재하면 호출, 아니면 무시
if (error.response?.status === 401 && !originalRequest._retry) {
이 코드는:
error.response가 존재하지 않으면 → undefined === 401 → false → if문 실행 안함error.response가 존재하면 → response.status === 401 체크네트워크 에러나 예상치 못한 에러 상황에서 response 객체가 없을 수 있기 때문에 이런 방어적 코딩이 필요합니다.
// ?? (Nullish Coalescing Operator)와 조합
const status = error.response?.status ?? 500
const message = error.response?.data?.message ?? 'Unknown error'
// 기본값 설정
const config = userConfig?.api?.timeout ?? 3000
Express.js 백엔드에서도 활용할 수 있습니다:
app.post('/api/user', (req, res) => {
const email = req.body?.user?.email
const preferences = req.body?.settings?.preferences ?? {}
if (!email) {
return res.status(400).json({ error: 'Email required' })
}
// ...
})
TypeScript를 사용한다면 Optional Chaining은 더욱 강력해짐.
타입 가드 역할도 하면서 타입 안정성을 높임