React - Exception Handling
Exception Handling
What is exception handling?
- When an error occurs during program execution, handling the error instead of continuing execution
Necessity
- Through exception handling, you can prevent abnormal program termination. - During program development, it can reduce the time needed to resolve issues when problems arise.
Types
Error Boundary
Features
- A new exception handling mechanism introduced starting with React 16 - Designed for declarative error management - A component that can handle errors originating from child components - When an error occurs in a child component, the parent component logs the error
- When an error occurs, displays a Fallback UI[^1] instead of the component where the error originated - Can handle errors occurring in render/useEffect - Cannot be used in event handlers or Hooks - However, errors that cannot be handled by an Error Boundary can be propagated using useErrorBoundary
Method
- static getDerivedStateFromError(): Used to update state in response to errors and display error messages to the user - componentDidCatch(): Logs errors related to services - Functions similarly to the catch{} statement but only operates within the component
Unusable situations
- Event handlers - Asynchronous code - Server-side rendering - Errors originating from the Error Boundary itself
How to Use
react // Subclass to define class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; }
static getDerivedStateFromError(error) { // Update state to show Fallback UI on next render return {hasError: true}; }
componentDidCatch(error, errorInfo) { // Can log the error to the error reporting service logErrorToMyService(error, errorInfo); }
render() { // Customize the Fallback UI to enable rendering return <> Fallback UI configuration </> } }
//Main component
- To use an Error Boundary, you must define it in a subclass as shown in the code above. - Afterward, you can wrap it with the defined subclass for use.
Throw
- It intentionally throws exceptions and handles them.
How to Use
Sample Code
} catch (error) { console.log(error); } } return( <> <button onClick={errorEvent}>예외 처리 버튼</button> </> ) }
//Output "Error: An exception occurred"
#### try-catch
**How to Use**
react try { // Code to execute } catch (exception variable name) { // Exception handling code } finally { // Optional // Code to execute after termination }
##### try
- Code to execute
##### catch
- The try block handles exceptions that may occur - Depending on the error type, it can be ignored or handled individually
##### finally
- The part that executes when the try block ends - Regardless of the try block, it executes **unconditionally** when execution ends
**Sample Code**
~~~react export default function App() { const obj = undefined; const errorEvent = () => { try{ console.log(obj.name) } catch(error){ console.log('오류발생 : ' + error); } finally{ console.log('수행 완료');
} } return( <> <button onClick={errorEvent}>예외 처리 버튼</button> </> ) }
--------------------------------------------------- //출력 "오류발생 : TypeError: Cannot read properties of undefined (reading 'name')" "수행 완료"
Try-Catch Exception Handling in Promise
- For promise[^2] objects, if await is not used as in the code above, exceptions cannot be handled with catch.
<br><br><br><br><br><br><br><br><br><br><br>
---
References
- [ERROR BOUNDARY 다루기(ErrorBoundary + react-error-boundary)](https://velog.io/@shyunju7/ERROR-BOUNDARY-%EB%8B%A4%EB%A3%A8%EA%B8%B0ErrorBoundary-react-error-boundary)
- [에러 경계(Error Boundaries)](https://ko.legacy.reactjs.org/docs/error-boundaries.html)
- [[JS/React] Try/Catch/Finally: A Late-Stage Approach to Exception Handling](https://velog.io/@double29/JSReact-%EB%92%A4%EB%8A%A6%EA%B2%8C-%EC%A0%95%EB%A6%AC%ED%95%98%EB%8A%94- The try/catch/finally exception handling pattern)
<br><br><br><br><br><br><br><br><br><br><br>
[^1]: A secondary UI that provides alternative functionality when the main UI is unavailable. [^2]: For details on [Promise]({{ site.baseurl }}/posts/비동기와-동기화), please refer to the link.
Found an error?
Open an issue on GitHub
Corrections will be incorporated with attribution.
Found a typo?
Fork, modify and open a PR.