Revert/Require를 활용한 오류 처리
견고한 계약 실행을 위해 `require()`, `revert()`, `assert()`를 사용한 효과적인 오류 처리 전략을 구현합니다.
Revert/Require를 활용한 오류 처리은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Robust Contracts: Error Handling
Welcome to error handling in Solidity! Writing smart contracts requires extreme care, as they often manage valuable assets and are immutable once deployed.
Effective error handling is crucial for creating robust and secure decentralized applications (dApps). It helps prevent unexpected behavior and protects users.
`require()`: Validating Inputs
The require() function is your primary tool for validating conditions that must be true before a function executes.
- It checks pre-conditions and user inputs.
- If the condition is false, it reverts all state changes made in the current transaction.
- It refunds any remaining gas to the caller, effectively canceling the transaction.
Use require() for external conditions and user-provided data checks.
`require()` in Action
Let's see require() in a simple contract. This function only allows users older than 18 to register.
pragma solidity ^0.8.0;
contract UserRegistration {
uint public minAge = 18;
address[] public registeredUsers;
function registerUser(uint _age) public {
// Validate user input: age must be at least minAge
require(_age >= minAge, "Must be 18 or older to register.");
registeredUsers.push(msg.sender);
}
}`revert()`: Flexible Error Handling
The revert() statement offers more flexibility than require(), especially when you need to handle complex error logic or integrate with custom error types.
- Like
require(), it reverts all state changes and refunds gas. - It's often used inside
ifstatements for more intricate conditional checks. - It can be called directly or with a string message, similar to
require().
Custom Errors with `revert()`
Solidity 0.8.4+ introduced Custom Errors. These are more gas-efficient than string messages and provide better clarity for off-chain applications.
You define custom errors at the contract or file level, then use them with revert(). They help reduce transaction costs and improve contract readability.
Custom Error Demo
Here's how to define and use a custom error with revert(). Notice the error keyword.
pragma solidity ^0.8.4;
contract Wallet {
address public owner;
uint public balance;
// Define a custom error
error InsufficientFunds(uint requested, uint available);
constructor() {
owner = msg.sender;
}
function deposit() public payable {
balance += msg.value;
}
function withdraw(uint _amount) public {
require(msg.sender == owner, "Only owner can withdraw.");
// Use revert() with the custom error
if (_amount > balance) {
revert InsufficientFunds(_amount, balance);
}
balance -= _amount;
payable(owner).transfer(_amount);
}
}`assert()`: Internal Invariants
The assert() function is used for a very specific purpose: checking internal invariants.
- It verifies conditions that should never be false if your code is working correctly.
- If an
assert()fails, it indicates a bug in your contract logic. - Crucially, a failed
assert()consumes all remaining gas, unlikerequire()andrevert()which refund gas.
Use assert() for post-conditions or internal consistency checks, not for user input validation.
When to Use Which?
Choosing the right error handler is key:
require(): For validating user inputs, external conditions, or state changes before execution. Refunds gas.revert(): For more complex error logic, often with custom errors. Also refunds gas.assert(): For internal consistency checks and invariants. Indicates a bug if it fails and consumes all gas.
Prioritize require() and revert() for expected errors, and reserve assert() for unexpected, internal errors.
Error Handling Check
You're building a function that transfers tokens. Before sending, you need to ensure the sender has enough balance. If not, the transaction should fail and refund any unused gas.
Recap: Error Handling
You've learned how to make your Solidity contracts robust with proper error handling:
require()is for validating external conditions and user inputs.revert()offers flexibility, often used with gas-efficient custom errors.assert()is for internal invariants, signaling a bug if it fails.
Mastering these ensures your smart contracts are secure and predictable. Great job!
자주 묻는 질문
“Revert/Require를 활용한 오류 처리” 강의는 무료인가요?
네 — “Revert/Require를 활용한 오류 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
“Revert/Require를 활용한 오류 처리”에서 뭘 배우나요?
견고한 계약 실행을 위해 `require()`, `revert()`, `assert()`를 사용한 효과적인 오류 처리 전략을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“Revert/Require를 활용한 오류 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 상속과 인터페이스
- 라이브러리와 추상 계약
- Revert/Require를 활용한 오류 처리
- 수정자와 검사-효과-상호 작용 패턴