Skip to content

Commit

Permalink
Core Lib Documentation: Panics module (#6785)
Browse files Browse the repository at this point in the history
Co-authored-by: enitrat <[email protected]>
  • Loading branch information
TAdev0 and enitrat authored Nov 29, 2024
1 parent d75d7df commit 17a7e9b
Showing 1 changed file with 51 additions and 2 deletions.
53 changes: 51 additions & 2 deletions corelib/src/panics.cairo
Original file line number Diff line number Diff line change
@@ -1,16 +1,65 @@
//! Core panic mechanism.
//!
//! This module provides the core panic functionality used for error handling in Cairo.
//! It defines the basic types and functions used to trigger and manage panics, which
//! are Cairo's mechanism for handling unrecoverable errors.
//!
//! Panics can be triggered in several ways:
//!
//! Using the `panic` function:
//!
//! ```
//! use core::panics::panic;
//!
//! panic(array!['An error occurred']);
//! ```
//!
//! Or using the `panic!` macro:
//!
//! ```
//! panic!("Panic message");
//! ```
//!
//! This macro internally converts the message into a `ByteArray` and uses `panic_with_byte_array`.

use crate::array::Array;

/// Represents a panic condition in Cairo.
///
/// A `Panic` is created when the program encounters an unrecoverable error condition
/// and needs to terminate execution.
pub struct Panic {}

/// Result type for operations that can trigger a panic.
pub enum PanicResult<T> {
Ok: T,
Err: (Panic, Array<felt252>),
}

/// Triggers an immediate panic with the provided data and terminates execution.
///
/// # Examples
///
/// ```
/// use core::panics::panic;
///
/// panic(array!['An error occurred']);
/// ```
pub extern fn panic(data: Array<felt252>) -> crate::never;

/// Panics with the given ByteArray. That is, panics with an `Array<felt252>` with
/// `BYTE_ARRAY_MAGIC`, and then the serialized given ByteArray.
/// Panics with a `ByteArray` message.
///
/// Constructs a panic message by prepending the `BYTE_ARRAY_MAGIC` value and
/// serializing the provided `ByteArray` into the panic data.
///
/// # Examples
///
/// ```
/// use core::panics::panic_with_byte_array;
///
/// let error_msg = "An error occurred";
/// panic_with_byte_array(@error_msg);
/// ```
#[inline]
pub fn panic_with_byte_array(err: @ByteArray) -> crate::never {
let mut serialized = array![crate::byte_array::BYTE_ARRAY_MAGIC];
Expand Down

0 comments on commit 17a7e9b

Please sign in to comment.