Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Binary Protocol

Type Mapping

Rust TypeTS/JS TypeKotlin Type
i8 ~ i64, u8 ~ u64, f32, f64numberInt/Long/Float/Double
boolbooleanBoolean
String, &strstringString
Vec<u8>Uint8ArrayByteArray
Option<T>T | nullT?
Vec<T>T[]List<T>
struct{ field: Type }data class
enum{ tag: 'Variant', data: ... }sealed class

Error Codes

System reserved error codes range from -90011 to -90000. User-defined errors must not use this range.

ConstantValueDescription
CODE_SIGNAL-90000OS signal (e.g., Ctrl+C)
CODE_MSG_TOO_SHORT-90001Message too short
CODE_PAYLOAD_MISMATCH-90002Payload length mismatch
CODE_SERIALIZE-90003Serialization/deserialization error
CODE_STATE_NOT_FOUND-90004State type not registered
CODE_HANDLER-90005Handler execution error
CODE_INVALID_PARAM-90006Invalid parameter
CODE_IO-90007I/O error
CODE_WS-90008WebSocket error
CODE_HTTP-90009HTTP error
CODE_TCP-90010TCP error
CODE_LONG_CONNECTION_NOT_SUPPORTED-90011Long connections unsupported in HTTP mode
CODE_RATE_LIMITED-90012Rate limit exceeded
#![allow(unused)]
fn main() {
// Custom error (code must be outside the reserved range)
return Err(afast::Error::custom(400, "invalid request parameter"));
}

Custom Error Types

Implement the AFastError trait to define your own error types and return Result<T, MyError> from handlers:

#![allow(unused)]
fn main() {
use afast::AFastError;

enum MyError {
    NotFound(String),
    Unauthorized,
}

impl AFastError for MyError {
    fn code(&self) -> i64 {
        match self {
            MyError::NotFound(_) => 404,
            MyError::Unauthorized => 401,
        }
    }

    fn message(&self) -> String {
        match self {
            MyError::NotFound(name) => format!("{} not found", name),
            MyError::Unauthorized => "unauthorized".into(),
        }
    }
}

#[handler(desc("Get user"))]
async fn get_user(id: Data<UserId>) -> afast::Result<UserInfo, MyError> {
    find_user(id).ok_or(MyError::NotFound("user".into()))
}
}

All handler macros (#[handler], #[get]/#[post]/#[put]/#[delete], #[ws], #[sse]) support custom error types. afast::Result<T> defaults to Error and is fully backward compatible.

Copied to clipboard!