Skip to content

Commit

Permalink
adds error attribute note
Browse files Browse the repository at this point in the history
  • Loading branch information
damirka committed Aug 27, 2024
1 parent 190e397 commit e7fcaf9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
13 changes: 12 additions & 1 deletion book/src/move-basics/assert-and-abort.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ The code above will, of course, abort with abort code `1`.
The `assert!` macro is a built-in macro that can be used to assert a condition. If the condition is
false, the transaction will abort with the given abort code. The `assert!` macro is a convenient way
to abort a transaction if a condition is not met. The macro shortens the code otherwise written with
an `if` expression + `abort`. The `code` argument is required and has to be a `u64` value.
an `if` expression + `abort`. The `code` argument is optional, but has to be a `u64` value or an
`#[error]` (see below for more information).

```move
{{#include ../../../packages/samples/sources/move-basics/assert-and-abort.move:assert}}
Expand All @@ -63,6 +64,16 @@ code and make it easier to understand the abort scenarios.
{{#include ../../../packages/samples/sources/move-basics/assert-and-abort.move:error_const}}
```

## Error messages

Move 2024 introduces a special type of error constant, marked with the `#[error]` attribute. This
attribute allows the error constant to be of type `vector<u8>` and can be used to store an error
message.

```move
{{#include ../../../packages/samples/sources/move-basics/assert-and-abort.move:error_attribute}}
```

## Further reading

- [Abort and Assert](/reference/abort-and-assert.html) in the Move Reference.
Expand Down
18 changes: 18 additions & 0 deletions packages/samples/sources/move-basics/assert-and-abort.move
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,22 @@ public fun update_record(/* ... , */ user_has_access: bool, field_exists: bool)
/* ... */
}
// ANCHOR_END: error_const

public struct User { is_authorized: bool, value: u64 }

// ANCHOR: error_attribute
#[error]
const ENotAuthorized: vector<u8> = b"The user is not authorized to perform this action";

#[error]
const EValueTooLow: vector<u8> = b"The value is too low, it should be at least 10";

/// Performs an action on behalf of the user.
public fun update_value(user: &mut User, value: u64) {
assert!(user.is_authorized, ENotAuthorized);
assert!(value >= 10, EValueTooLow);

user.value = value;
}
// ANCHOR_END: error_attribute
}

0 comments on commit e7fcaf9

Please sign in to comment.