Obsługa błędów za pomocą Revert/Require
Implementuj skuteczną obsługę błędów za pomocą `require()`, `revert()` i `assert()`, aby zapewnić niezawodne wykonywanie kontraktów.
Obsługa błędów za pomocą Revert/Require to bezpłatna lekcja Blockchain Smart Contracts with Solidity na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Blockchain Smart Contracts with Solidity, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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!
Często zadawane pytania
Czy lekcja „Obsługa błędów za pomocą Revert/Require” jest bezpłatna?
Tak — pełny tekst „Obsługa błędów za pomocą Revert/Require” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Blockchain Smart Contracts with Solidity, przejdź na CoddyKit PRO. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.
Co nauczysz się w „Obsługa błędów za pomocą Revert/Require”?
Implementuj skuteczną obsługę błędów za pomocą `require()`, `revert()` i `assert()`, aby zapewnić niezawodne wykonywanie kontraktów. Ćwiczysz Blockchain Smart Contracts with Solidity z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Blockchain Smart Contracts with Solidity?
Nie wymagamy żadnego doświadczenia. Blockchain Smart Contracts with Solidity w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.
Ile czasu zajmuje lekcja „Obsługa błędów za pomocą Revert/Require”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Blockchain Smart Contracts with Solidity?
Tak. Każda lekcja Blockchain Smart Contracts with Solidity zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Dziedziczenie i interfejsy
- Biblioteki i kontrakty abstrakcyjne
- Obsługa błędów za pomocą Revert/Require
- Modyfikatory i wzorzec Checks-Effects-Interactions