-
Notifications
You must be signed in to change notification settings - Fork 249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Standardize errors #1165
Open
PolyProgrammist
wants to merge
89
commits into
near:master
Choose a base branch
from
PolyProgrammist:standartize-errors
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Standardize errors #1165
Changes from all commits
Commits
Show all changes
89 commits
Select commit
Hold shift + click to select a range
7260447
tmp
PolyProgrammist 9ec4723
add persist_on_error
PolyProgrammist d5d5298
Merge branch 'master' into standartize-errors
PolyProgrammist f4a27e0
add another project, remove status, add approximate promise call
PolyProgrammist 1243da8
simple project with simple test
PolyProgrammist 5d166e7
add error method and call to it to the contract
PolyProgrammist 56e5549
tmp
PolyProgrammist 9c22faa
add state_write
PolyProgrammist b005c35
fix handle result and enable tests
PolyProgrammist 53ef6fd
fix FunctionError::panic to panic_str and added a test that checks er…
PolyProgrammist 3a2a41a
add json serialization automatically
PolyProgrammist 1d4ec49
add struct to tests
PolyProgrammist b79ece8
use check_trait for standard errors instead of handle_result
PolyProgrammist 8cfa0da
remove asref
PolyProgrammist 1d2b594
tmp
PolyProgrammist c2b397a
made methods for promises generate by #[near]. pass error argument to…
PolyProgrammist 47ad490
generate error function only if it has persist on error
PolyProgrammist 0b37e7c
add error type name to output
PolyProgrammist eceb288
add abi for result OK
PolyProgrammist d35d1cf
refactor error-handling example, remove debug files
PolyProgrammist 7ecede5
refactor: remove commented code, use HandlesResultExplicit and Handle…
PolyProgrammist 4ee2aba
refactor errorwrapper
PolyProgrammist 7a14556
fmt
PolyProgrammist 48576b2
fix standartized -> standardized, return compilation tests back, fix …
PolyProgrammist 966d400
refactor
PolyProgrammist 7ec7ac4
refactor
PolyProgrammist 9f96ec1
fix abi & fmt
PolyProgrammist 52a426c
fix clippy and readme
PolyProgrammist 8935303
ci: fix new 1.78 lints
aea83c7
test: `schemars` version update, `TRYBUILD=overwrite`
b427177
move functions above tests to fix clippy
PolyProgrammist 74b54ea
fix compilation test
PolyProgrammist 81c9559
refactor ResultTypeExt
PolyProgrammist 8409206
fixed snapshot tests by moving contract_ser out of handle_error and s…
PolyProgrammist 352a873
remove tests without handle_result
PolyProgrammist 8167824
fix snap tests and add for new feature
PolyProgrammist 26c2620
return 1 test
PolyProgrammist 160651e
remove returns and add docs
PolyProgrammist d497ccd
Merge branch 'master' into standartize-errors
PolyProgrammist c646470
add cause
PolyProgrammist 52e1041
add sdk contract error
PolyProgrammist adbffbc
add baseerror
PolyProgrammist 080250e
add snapshot for generated method_error
PolyProgrammist 745fe09
fmt
PolyProgrammist ca84208
fix clippy
PolyProgrammist 8e3a59c
fix compilation tests
PolyProgrammist 17df48c
add compilation failed test for incorrect result
PolyProgrammist 64cf673
fix comp test
PolyProgrammist 6e39ba3
tmp
PolyProgrammist 2f837cc
add standard error and use it in one example, add inside_nearsdk for …
PolyProgrammist 63ec033
add wrap_error and use it in PanicOnDefault
PolyProgrammist bd96f6d
add wrap to impl
PolyProgrammist 2dfa359
move wrap outside standardized_error_panic_tokens
PolyProgrammist 14e2b94
use string from instead of wrap
PolyProgrammist 0ed933e
switch to new errors in examples for panic_str and require
PolyProgrammist 67230f9
return err instead of panic
PolyProgrammist ed3e2c9
update some panic_strs in near-contract-standards
PolyProgrammist acee075
add unwrap_or_err, unwrap_or_return, fixed panic_str for near-contrac…
PolyProgrammist 556e18d
introduce require_or_err
PolyProgrammist a82fc23
fix fungible token example
PolyProgrammist 43a0360
fmt
PolyProgrammist 43ac3ef
fix comilation tests
PolyProgrammist a49df2d
fix clippy ident : this creates an owned instance just for comparison
PolyProgrammist 410d621
fix clippy & fungible
PolyProgrammist 3564b20
fix clippy multiple things
PolyProgrammist 93c47e2
fix fungible token test
PolyProgrammist c0f4a90
fix snapshots
PolyProgrammist 47aec44
fix some problems in test core macos (comments)
PolyProgrammist 9f2f4f0
flatten BaseError
PolyProgrammist 7e5574f
fix snaps
PolyProgrammist 89d8552
separate String::from implementation for BaseError
PolyProgrammist b0d0d5e
panic_str to panic_err in some cases
PolyProgrammist 70e219b
panic_str to panic_err for serialization / deserialization, inconsist…
PolyProgrammist ee90f67
more panic_str to panic_err
PolyProgrammist b8e388b
all panic_str to panic_err
PolyProgrammist 7b31261
fmt
PolyProgrammist f5e9db6
fix compilation test
PolyProgrammist 9d2c9db
fix fungilbe token build
PolyProgrammist 2e90e0f
fix clippy & invalid range expect tests
PolyProgrammist fb636c1
fix snaps
PolyProgrammist fe9fd69
renamings
PolyProgrammist 6e4349a
AnyError to Error, try to avoid
PolyProgrammist b9a2282
divide sdk & custom errors
PolyProgrammist ba588e5
fmt
PolyProgrammist eb386b4
require to require_or_err in near-contract-standards and examples
PolyProgrammist 6a0096a
fix tests
PolyProgrammist 666eb9f
fix macos tests
PolyProgrammist 873627c
add docs
PolyProgrammist 65a23af
fix commented examples
PolyProgrammist File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
[target.wasm32-unknown-unknown] | ||
rustflags = ["-C", "link-arg=-s"] | ||
|
||
[build] | ||
target-dir = "../../target" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
[package] | ||
name = "error-handling" | ||
version = "0.1.0" | ||
authors = ["Near Inc <[email protected]>"] | ||
edition = "2021" | ||
|
||
[lib] | ||
crate-type = ["cdylib"] | ||
|
||
[dependencies] | ||
near-sdk = { path = "../../near-sdk" } | ||
|
||
[dev-dependencies] | ||
near-workspaces = { version = "0.9.0", default-features = false, features = ["install"] } | ||
test-case = "2.0" | ||
tokio = { version = "1.14", features = ["full"] } | ||
anyhow = "1.0" | ||
|
||
[profile.release] | ||
codegen-units = 1 | ||
# Tell `rustc` to optimize for small code size. | ||
opt-level = "z" | ||
lto = true | ||
debug = false | ||
panic = "abort" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
# error-handling | ||
|
||
cargo-near-new-project-description | ||
|
||
## How to Build Locally? | ||
|
||
Install [`cargo-near`](https://github.com/near/cargo-near) and run: | ||
|
||
```bash | ||
cargo near build | ||
``` | ||
|
||
## How to Test Locally? | ||
|
||
```bash | ||
cargo test | ||
``` | ||
|
||
## How to Deploy? | ||
|
||
Deployment is automated with GitHub Actions CI/CD pipeline. | ||
To deploy manually, install [`cargo-near`](https://github.com/near/cargo-near) and run: | ||
|
||
```bash | ||
cargo near deploy <account-id> | ||
``` | ||
|
||
## Useful Links | ||
|
||
- [cargo-near](https://github.com/near/cargo-near) - NEAR smart contract development toolkit for Rust | ||
- [near CLI](https://near.cli.rs) - Interact with NEAR blockchain from command line | ||
- [NEAR Rust SDK Documentation](https://docs.near.org/sdk/rust/introduction) | ||
- [NEAR Documentation](https://docs.near.org) | ||
- [NEAR StackOverflow](https://stackoverflow.com/questions/tagged/nearprotocol) | ||
- [NEAR Discord](https://near.chat) | ||
- [NEAR Telegram Developers Community Group](https://t.me/neardev) | ||
- NEAR DevHub: [Telegram](https://t.me/neardevhub), [Twitter](https://twitter.com/neardevhub) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
#!/bin/bash | ||
TARGET="${CARGO_TARGET_DIR:-../../target}" | ||
set -e | ||
cd "$(dirname $0)" | ||
|
||
cargo build --all --target wasm32-unknown-unknown --release | ||
cp $TARGET/wasm32-unknown-unknown/release/error_handling.wasm ./res/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
// Find all our documentation at https://docs.near.org | ||
use near_sdk::contract_error; | ||
use near_sdk::near; | ||
use near_sdk::BaseError; | ||
|
||
#[contract_error] | ||
pub enum MyErrorEnum { | ||
X, | ||
} | ||
|
||
#[contract_error(sdk)] | ||
pub struct MyErrorStruct { | ||
x: u32, | ||
} | ||
|
||
#[near(contract_state)] | ||
#[derive(Default)] | ||
pub struct Contract { | ||
value: u32, | ||
} | ||
|
||
#[near] | ||
impl Contract { | ||
#[init] | ||
pub fn new() -> Self { | ||
Self { value: 0 } | ||
} | ||
|
||
// Examples of RPC response for function call: | ||
// is_error = false | ||
// --- Result ------------------------- | ||
// 1 | ||
// ------------------------------------ | ||
// (changes value from 0 to 1) | ||
// | ||
// is_error = true | ||
// Failed transaction | ||
// Error: | ||
// 0: Error: An error occurred during a `FunctionCall` Action, parameter is debug message. | ||
// ExecutionError("Smart contract panicked: error in inc_handle_result") | ||
// (does not change value) | ||
#[handle_result] | ||
pub fn inc_handle_result(&mut self, is_error: bool) -> Result<u32, &'static str> { | ||
self.value += 1; | ||
if is_error { | ||
Err("error in inc_handle_result") | ||
} else { | ||
Ok(self.value) | ||
} | ||
} | ||
|
||
// Examples of RPC response for function call: | ||
// is_error = false | ||
// --- Result ------------------------- | ||
// 2 | ||
// ------------------------------------ | ||
// (changes value from 1 to 2) | ||
// | ||
// is_error = true | ||
// Failed transaction | ||
// Error: | ||
// 0: Error: An error occurred during a `FunctionCall` Action, parameter is debug message. | ||
// ExecutionError("Smart contract panicked: {\"error\":{\"error_type\":\"error_handling::MyErrorEnum\",\"value\":\"X\"}}") | ||
// (changes value from 2 to 3) | ||
#[persist_on_error] | ||
pub fn inc_persist_on_err(&mut self, is_error: bool) -> Result<u32, MyErrorEnum> { | ||
self.value += 1; | ||
if is_error { | ||
Err(MyErrorEnum::X) | ||
} else { | ||
Ok(self.value) | ||
} | ||
} | ||
|
||
// Examples of RPC response for function call: | ||
// is_error = false | ||
// --- Result ------------------------- | ||
// 4 | ||
// ------------------------------------ | ||
// (changes value from 3 to 4) | ||
// | ||
// is_error = true | ||
// Failed transaction | ||
// Error: | ||
// 0: Error: An error occurred during a `FunctionCall` Action, parameter is debug message. | ||
// ExecutionError("Smart contract panicked: {\"error\":{\"error_type\":\"error_handling::MyErrorStruct\",\"value\":{\"x\":5}}}") | ||
// (does not change value) | ||
pub fn inc_just_result(&mut self, is_error: bool) -> Result<u32, MyErrorStruct> { | ||
self.value += 1; | ||
if is_error { | ||
Err(MyErrorStruct { x: 5 }) | ||
} else { | ||
Ok(self.value) | ||
} | ||
} | ||
|
||
// Examples of RPC response for function call: | ||
// is_error = false | ||
// --- Result ------------------------- | ||
// 5 | ||
// ------------------------------------ | ||
// (changes value from 4 to 5) | ||
// | ||
// is_error = true | ||
// Failed transaction | ||
// Error: | ||
// 0: Error: An error occurred during a `FunctionCall` Action, parameter is debug message. | ||
// ExecutionError("Smart contract panicked: Error") | ||
// (does not change value) | ||
pub fn inc_just_simple(&mut self, is_error: bool) -> u32 { | ||
self.value += 1; | ||
if is_error { | ||
::near_sdk::env::panic_str("Error"); | ||
} else { | ||
self.value | ||
} | ||
} | ||
|
||
// Examples of RPC response for function call: | ||
// is_error = false | ||
// --- Result ------------------------- | ||
// 6 | ||
// ------------------------------------ | ||
// (changes value from 5 to 6) | ||
// | ||
// is_error = true | ||
// Failed transaction | ||
// Error: | ||
// 0: Error: An error occurred during a `FunctionCall` Action, parameter is debug message. | ||
// ExecutionError("Smart contract panicked: {\\\"error\\\":{\\\"cause\\\":{\\\"info\\\":{\\\"error\\\":{\\\"x\\\":5}},\\\"name\\\":\\\"near_sdk::utils::contract_error::BaseError\\\"},\\\"name\\\":\\\"CUSTOM_CONTRACT_ERROR\\\"}}") | ||
// (does not change value) | ||
pub fn inc_base_error(&mut self, is_error: bool) -> Result<u32, BaseError> { | ||
self.value += 1; | ||
if is_error { | ||
Err(MyErrorStruct { x: 5 }.into()) | ||
} else { | ||
Ok(self.value) | ||
} | ||
} | ||
|
||
// Does not compile as u64 is not marked with contract_error | ||
// > the trait `ContractErrorTrait` is not implemented for `u64` | ||
// pub fn inc_incorrect_result_type(&mut self, is_error: bool) -> Result<u32, u64> { | ||
// self.value += 1; | ||
// if is_error { | ||
// Err(0) | ||
// } else { | ||
// Ok(self.value) | ||
// } | ||
// } | ||
|
||
pub fn get_value(&self) -> u32 { | ||
self.value | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
use near_sdk::serde_json; | ||
use near_workspaces::Contract; | ||
use serde_json::json; | ||
|
||
async fn get_value(contract: &Contract) -> anyhow::Result<u64> { | ||
let get_value: serde_json::Value = | ||
contract.call("get_value").args_json(json!({})).view().await?.json()?; | ||
|
||
println!("get_value: {:?}", get_value); | ||
|
||
get_value.as_u64().ok_or_else(|| anyhow::anyhow!("get_value is not a u64")) | ||
} | ||
|
||
async fn check_call( | ||
contract: &Contract, | ||
method: &str, | ||
is_error: bool, | ||
expected_value: u64, | ||
expected_error: Option<String>, | ||
) { | ||
let res = contract | ||
.call(method) | ||
.args_json(json!({ "is_error": is_error })) | ||
.max_gas() | ||
.transact() | ||
.await | ||
.unwrap(); | ||
if is_error { | ||
assert!(res.is_failure()); | ||
if let Some(expected_error) = expected_error { | ||
let string_error = | ||
format!("{:?}", res.failures()[0].clone().into_result().unwrap_err()); | ||
assert_eq!(string_error, expected_error); | ||
} | ||
} else { | ||
assert!(res.is_success()); | ||
} | ||
assert_eq!(get_value(&contract).await.unwrap(), expected_value); | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_error_handling() -> anyhow::Result<()> { | ||
let worker = near_workspaces::sandbox().await?; | ||
let contract = | ||
worker.dev_deploy(&std::fs::read(format!("res/{}.wasm", "error_handling"))?).await?; | ||
|
||
check_call(&contract, "inc_handle_result", false, 1, None).await; | ||
check_call(&contract, "inc_persist_on_err", false, 2, None).await; | ||
check_call(&contract, "inc_just_result", false, 3, None).await; | ||
check_call(&contract, "inc_just_simple", false, 4, None).await; | ||
check_call(&contract, "inc_base_error", false, 5, None).await; | ||
check_call(&contract, "inc_handle_result", true, 5, None).await; | ||
check_call(&contract, "inc_persist_on_err", true, 6, Some("Error { repr: Custom { kind: Execution, error: ActionError(ActionError { index: Some(0), kind: FunctionCallError(ExecutionError(\"Smart contract panicked: {\\\"error\\\":{\\\"cause\\\":{\\\"info\\\":\\\"X\\\",\\\"name\\\":\\\"error_handling::MyErrorEnum\\\"},\\\"name\\\":\\\"CUSTOM_CONTRACT_ERROR\\\"}}\")) }) } }".to_string())).await; | ||
check_call(&contract, "inc_just_result", true, 6, Some("Error { repr: Custom { kind: Execution, error: ActionError(ActionError { index: Some(0), kind: FunctionCallError(ExecutionError(\"Smart contract panicked: {\\\"error\\\":{\\\"cause\\\":{\\\"info\\\":{\\\"x\\\":5},\\\"name\\\":\\\"error_handling::MyErrorStruct\\\"},\\\"name\\\":\\\"SDK_CONTRACT_ERROR\\\"}}\")) }) } }".to_string())).await; | ||
check_call(&contract, "inc_base_error", true, 6, Some("Error { repr: Custom { kind: Execution, error: ActionError(ActionError { index: Some(0), kind: FunctionCallError(ExecutionError(\"Smart contract panicked: {\\\"error\\\":{\\\"cause\\\":{\\\"info\\\":{\\\"error\\\":{\\\"x\\\":5}},\\\"name\\\":\\\"near_sdk::utils::contract_error::BaseError\\\"},\\\"name\\\":\\\"CUSTOM_CONTRACT_ERROR\\\"}}\")) }) } }".to_string())).await; | ||
check_call(&contract, "inc_just_simple", true, 6, None).await; | ||
|
||
Ok(()) | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's provide doc strings that illustrate the potential return values from the RPC response point of view.
P.S. Apply the same reasoning below