//! The error type every engine entry point returns. use serde::Serialize; /// Why a command could not run or failed. /// /// Each variant has a stable [`code`](EngineError::code) that the control /// channel, MCP and the frontend use to tell errors apart. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum EngineError { /// No command is registered under the id. #[error("unknown command: {0}")] UnknownCommand(String), /// The command exists but is disabled in the current state. #[error("command is not available right now: {0}")] Disabled(String), /// The params do not match the command's documented schema. #[error("invalid params for {command}: {message}")] InvalidParams { /// The command id. command: String, /// What is wrong with the params. message: String, }, /// An edit was based on an older version of the buffer than the engine /// holds. The caller resynchronises (`buffer.get`) and retries. #[error("buffer {id} is at version {current}, the edit was based on version {base}")] StaleVersion { /// The buffer id. id: u64, /// The version the caller based its edit on. base: u64, /// The engine's current version. current: u64, }, /// The action would discard unsaved changes; repeat it with `force` to /// discard them. #[error("{0} has unsaved changes")] UnsavedChanges(String), /// The command ran and failed, e.g. a file could not be read. #[error("{0}")] Failed(String), /// A bug: a command panicked or reached a state it should not. The guard /// reports panics with this variant. #[error("internal error: {0}")] Internal(String), } impl EngineError { /// Stable machine-readable code of the error. pub fn code(&self) -> &'static str { match self { Self::UnknownCommand(_) => "unknown_command", Self::Disabled(_) => "disabled", Self::InvalidParams { .. } => "invalid_params", Self::StaleVersion { .. } => "stale_version", Self::UnsavedChanges(_) => "unsaved_changes", Self::Failed(_) => "failed", Self::Internal(_) => "internal", } } /// Shorthand for [`EngineError::InvalidParams`]. pub fn invalid_params(command: &str, message: impl Into) -> Self { Self::InvalidParams { command: command.to_string(), message: message.into(), } } /// The error as a `{ code, message }` payload for IPC and the control /// channel. pub fn payload(&self) -> ErrorPayload { ErrorPayload { code: self.code().to_string(), message: self.to_string(), } } } /// Serialisable form of an [`EngineError`]. #[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)] pub struct ErrorPayload { /// Stable code, see [`EngineError::code`]. pub code: String, /// Message for the user. pub message: String, } #[cfg(test)] mod tests { use super::*; #[test] fn codes_are_stable() { assert_eq!( EngineError::UnknownCommand("x".into()).code(), "unknown_command" ); let e = EngineError::InvalidParams { command: "a.b".into(), message: "missing path".into(), }; assert_eq!(e.payload().code, "invalid_params"); assert_eq!(e.payload().message, "invalid params for a.b: missing path"); } }