Error Boundary 컴포넌트
Error Boundary는 애플리케이션의 어느 부분이든 감싸서 예상치 못한 오류를 격리하는 컴포넌트예요. 하위 트리에서 발생하는 클라이언트 측 오류를 포착해 폴백(fallback) 메시지를 보여 줘요. 페이지 수준·섹션 수준 범위와 독립형(standalone)·내장형(built-in) 유형을 설명하고, 통합 테스트에서 폴백을 강제로 표시하는 방법도 제공해요.
출처: 문서
본문
Error boundary
Rendered around any part of the application to isolate unexpected errors.
애플리케이션의 어느 부분이든 감싸서 예상치 못한 오류를 격리하는 데 사용돼요.
Development guidelines
Error boundaries setup
error boundary 컴포넌트는 애플리케이션의 어느 부분이든 감싸서 하위 트리에서 발생하는 클라이언트 측 오류를 포착할 수 있어요. 이 컴포넌트는 내장된 국제화에 의존하므로, I18nProvider 안에서 렌더링하거나 사용자 정의 i18nStrings 설정을 제공해야 해요.
app layout, container, modal, table 등 많은 Cloudscape 컴포넌트에는 컴포넌트 트리 위쪽에 독립형 error boundary가 존재할 때 활성화되는 내장 error boundary가 포함돼 있어요. 따라서 이들 컴포넌트 내에서 발생한 오류는 실패 지점에 더 가까운 폴백 메시지를 표시하고, 컴포넌트 계층 위로 더 전파되지 않아요.
그 결과, 권장되는 최소 설정은 전체 애플리케이션을 감싸는 단일 error boundary 컴포넌트를 포함하는 거예요.
<I18nProvider locale={locale} messages={[messages]}>
<ErrorBoundary onError={logError}>
<App />
</ErrorBoundary>
</I18nProvider>
테스트 유틸리티 클래스가 처음이라면 소개 문서에서 더 자세히 알아볼 수 있어요.
Testing guidelines
Showing error boundary fallback in integration tests
error boundary는 요소 인스턴스에 요청 시 폴백 메시지를 표시하는 작은 테스트 API를 노출해요. 통합 테스트에서 이 메커니즘을 사용해서:
- 폴백의 외형과 콘텐츠를 검증할 수 있어요.
- 테스트를 위해 실제 런타임 오류를 유발하지 않을 수 있어요.
import createWrapper from '@cloudscape-design/components/test-utils/selectors';
// Select the error boundary root using the `errorBoundaryId` passed to <ErrorBoundary />.
const errorBoundaryRootSelector = `[data-awsui-error-boundary-id="{errorBoundaryId}"]`;
const errorBoundaryRootElement = document.querySelector(errorBoundaryRootSelector);
// Force the error boundary into its fallback state.
// Note: this does NOT invoke the onError() callback.
errorBoundaryRootElement.__awsui__.forceError();
// Query the rendered error boundary fallback (assuming only one visible at a time).
const errorBoundaryFallbackSelector = createWrapper().findErrorBoundary().toSelector();
const errorBoundaryFallbackElement = document.querySelector(errorBoundaryFallbackSelector);
expect(errorBoundaryFallbackElement).toHaveTextContent(expectedContent);
// Restore the normal state when the test is done (unless there is an actual error to be shown).
errorBoundaryRootElement.__awsui__.clearForcedError();
Unit testing APIs
ErrorBoundaryWrapper
| Name | Return type | Description | Parameters |
|---|---|---|---|
| findAction | ElementWrapper | null | - | - |
| findDescription | ElementWrapper | - | - |
| findFeedbackAction | ElementWrapper | null | - | - |
| findHeader | ElementWrapper | - | - |
| findRefreshAction | ElementWrapper | null | - | - |
Integration testing APIs
ErrorBoundaryWrapper
| Name | Return type | Description | Parameters |
|---|---|---|---|
| findAction | ElementWrapper | - | - |
| findDescription | ElementWrapper | - | - |
| findFeedbackAction | ElementWrapper | - | - |
| findHeader | ElementWrapper | - | - |
| findRefreshAction | ElementWrapper | - | - |
General guidelines
Do
- 애플리케이션에서 예상치 못한 JavaScript 오류를 처리하려면 error boundary를 사용하세요.
- 전체 애플리케이션에서 처리되지 않은 오류를 잡기 위해 최상위(top-level) error boundary를 구현하세요.
- 사용자 정의 컴포넌트나 다른 폴백 경험이 필요할 때만 섹션 수준 error boundary를 추가하세요. 예를 들어 기본 "Refresh page" 동작을 상황에 맞는 "Reload section"으로 바꿀 때요.
Don't
- 폴백 메시지가 달라야 할 필요가 없다면 애플리케이션 섹션이나 컴포넌트를 error boundary로 감싸는 것은 피하세요.
- 예상되는 오류나 비동기 오류를 처리하는 데 error boundary를 사용하지 마세요 (대신 try-catch를 사용하세요).
Features
Fallback structure
폴백은 오류가 포착되었을 때 나타나며, 일반적으로 오류 알림에 표시돼요. 폴백 메시지의 모든 부분은 사용자 정의할 수 있어서, 지역화나 맞춤 메시지가 가능해요.
기본적으로 세 가지 요소가 포함돼요:
-
Header
무엇이 잘못되었는지에 대한 짧고 직접적인 진술이에요. 예를 들어: "Unexpected error, content failed to show" . -
Description
간결한 설명이나 제안된 다음 단계예요. 예를 들어: "Refresh to try again. We're tracking the issue" . 선택적인 피드백 링크와 함께 제공돼요. -
Action
가장 관련성 높은 다음 단계를 위한 단일 primary 버튼이에요. 예를 들어: "Refresh page" .
Types
-
Standalone
감싼 콘텐츠 내에서 오류가 발생하면 전체 섹션이 오류 폴백으로 대체돼요. 이를 통해 애플리케이션의 특정 부분을 error boundary로 감싸서 오류 처리를 세밀하게 제어할 수 있어요. -
Built-in
app layout 콘텐츠, container, modal, drawer 같은 일부 Cloudscape 컴포넌트에는 내장 error boundary가 있어요. 이들은 컴포넌트 계층 위쪽에 있는 가장 가까운 독립형 error boundary 컴포넌트에서 설정을 가져와요. 즉, 내장 error boundary가 있는 Cloudscape 컴포넌트 내에서 오류가 발생하면 컴포넌트 트리 위쪽으로 전파되는 대신 내장 error boundary가 폴백 메시지를 표시해요.
Scope
Error boundary는 애플리케이션에서 다른 범위에 적용될 수 있어요:
- 페이지 수준(Page-level): 전체 페이지에 영향을 주는 치명적인 오류를 처리해요.
- 섹션 수준(Section-level): 페이지의 특정 부분에서 발생하는 오류를 처리해요.
페이지 대 섹션 boundary를 언제 사용할지에 대한 자세한 지침은 오류 유형을 참고하세요.