From e7fcaf9e6befe65465a096bddd07366a1598d9a9 Mon Sep 17 00:00:00 2001 From: Damir Shamanaev Date: Tue, 27 Aug 2024 15:15:54 +0300 Subject: [PATCH] adds error attribute note --- book/src/move-basics/assert-and-abort.md | 13 ++++++++++++- .../sources/move-basics/assert-and-abort.move | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/book/src/move-basics/assert-and-abort.md b/book/src/move-basics/assert-and-abort.md index 27aa0908..319dc4eb 100644 --- a/book/src/move-basics/assert-and-abort.md +++ b/book/src/move-basics/assert-and-abort.md @@ -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}} @@ -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` 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. diff --git a/packages/samples/sources/move-basics/assert-and-abort.move b/packages/samples/sources/move-basics/assert-and-abort.move index a388bb7d..595c1dd4 100644 --- a/packages/samples/sources/move-basics/assert-and-abort.move +++ b/packages/samples/sources/move-basics/assert-and-abort.move @@ -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 = b"The user is not authorized to perform this action"; + +#[error] +const EValueTooLow: vector = 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 }