1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
//! This module defines different errors occurring during communication with MPD.
//!
//! There're following kinds of possible errors:
//!
//! - IO errors (due to network communication failures),
//! - parsing errors (because of bugs in parsing server response),
//! - protocol errors (happen when we get unexpected data from server,
//! mostly because protocol version mismatch, network data corruption
//! or just bugs in the client),
//! - server errors (run-time errors coming from MPD due to some MPD
//! errors, like database failures or sound problems)
//!
//! This module defines all necessary infrastructure to represent these kinds or errors.
use std::convert::From;
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IoError;
use std::num::{ParseFloatError, ParseIntError};
use std::result;
use std::str::FromStr;
use std::string::ParseError as StringParseError;
// Server errors {{{
/// Server error codes, as defined in [libmpdclient](http://www.musicpd.org/doc/libmpdclient/protocol_8h_source.html)
#[cfg_attr(feature = "serde", derive(serde_repr::Serialize_repr, serde_repr::Deserialize_repr))]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum ErrorCode {
/// not a list
NotList = 1,
/// bad command arguments
Argument = 2,
/// invalid password
Password = 3,
/// insufficient permissions
Permission = 4,
/// unknown command
UnknownCmd = 5,
/// object doesn't exist
NoExist = 50,
/// maximum playlist size exceeded
PlaylistMax = 51,
/// general system error
System = 52,
/// error loading playlist
PlaylistLoad = 53,
/// update database is already in progress
UpdateAlready = 54,
/// player synchronization error
PlayerSync = 55,
/// object already exists
Exist = 56,
}
impl FromStr for ErrorCode {
type Err = ParseError;
fn from_str(s: &str) -> result::Result<ErrorCode, ParseError> {
use self::ErrorCode::*;
match s.parse()? {
1 => Ok(NotList),
2 => Ok(Argument),
3 => Ok(Password),
4 => Ok(Permission),
5 => Ok(UnknownCmd),
50 => Ok(NoExist),
51 => Ok(PlaylistMax),
52 => Ok(System),
53 => Ok(PlaylistLoad),
54 => Ok(UpdateAlready),
55 => Ok(PlayerSync),
56 => Ok(Exist),
v => Err(ParseError::BadErrorCode(v)),
}
}
}
impl StdError for ErrorCode {}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ErrorCode::*;
let desc = match *self {
NotList => "not a list",
Argument => "invalid argument",
Password => "invalid password",
Permission => "permission",
UnknownCmd => "unknown command",
NoExist => "item not found",
PlaylistMax => "playlist overflow",
System => "system",
PlaylistLoad => "playload load",
UpdateAlready => "already updating",
PlayerSync => "player syncing",
Exist => "already exists",
};
f.write_str(desc)
}
}
/// Server error
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct ServerError {
/// server error code
pub code: ErrorCode,
/// command position in command list
pub pos: u16,
/// command name, which caused the error
pub command: String,
/// detailed error description
pub detail: String,
}
impl StdError for ServerError {}
impl fmt::Display for ServerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} error (`{}') at {}", self.code, self.detail, self.pos)
}
}
impl FromStr for ServerError {
type Err = ParseError;
fn from_str(s: &str) -> result::Result<ServerError, ParseError> {
// ACK [<code>@<index>] {<command>} <description>
if let Some(s) = s.strip_prefix("ACK [") {
if let (Some(atsign), Some(right_bracket)) = (s.find('@'), s.find(']')) {
match (s[..atsign].parse(), s[atsign + 1..right_bracket].parse()) {
(Ok(code), Ok(pos)) => {
let s = &s[right_bracket + 1..];
if let (Some(left_brace), Some(right_brace)) = (s.find('{'), s.find('}')) {
let command = s[left_brace + 1..right_brace].to_string();
let detail = s[right_brace + 1..].trim().to_string();
Ok(ServerError { code, pos, command, detail })
} else {
Err(ParseError::NoMessage)
}
}
(Err(_), _) => Err(ParseError::BadCode),
(_, Err(_)) => Err(ParseError::BadPos),
}
} else {
Err(ParseError::NoCodePos)
}
} else {
Err(ParseError::NotAck)
}
}
}
// }}}
// Error {{{
/// Main error type, describing all possible error classes for the crate
#[derive(Debug)]
pub enum Error {
/// IO errors (low-level network communication failures)
Io(IoError),
/// parsing errors (unknown data came from server)
Parse(ParseError),
/// protocol errors (e.g. missing required fields in server response, no handshake message etc.)
Proto(ProtoError),
/// server errors (a.k.a. `ACK` responses from server)
Server(ServerError),
}
/// Shortcut type for MPD results
pub type Result<T> = result::Result<T, Error>;
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match *self {
Error::Io(ref err) => Some(err),
Error::Parse(ref err) => Some(err),
Error::Proto(ref err) => Some(err),
Error::Server(ref err) => Some(err),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Io(ref err) => err.fmt(f),
Error::Parse(ref err) => err.fmt(f),
Error::Proto(ref err) => err.fmt(f),
Error::Server(ref err) => err.fmt(f),
}
}
}
impl From<IoError> for Error {
fn from(e: IoError) -> Error {
Error::Io(e)
}
}
impl From<ParseError> for Error {
fn from(e: ParseError) -> Error {
Error::Parse(e)
}
}
impl From<ProtoError> for Error {
fn from(e: ProtoError) -> Error {
Error::Proto(e)
}
}
impl From<ParseIntError> for Error {
fn from(e: ParseIntError) -> Error {
Error::Parse(ParseError::BadInteger(e))
}
}
impl From<ParseFloatError> for Error {
fn from(e: ParseFloatError) -> Error {
Error::Parse(ParseError::BadFloat(e))
}
}
impl From<ServerError> for Error {
fn from(e: ServerError) -> Error {
Error::Server(e)
}
}
// }}}
// Parse errors {{{
/// Parsing error kinds
#[derive(Debug, Clone, PartialEq)]
pub enum ParseError {
/// invalid integer
BadInteger(ParseIntError),
/// invalid float
BadFloat(ParseFloatError),
/// some other invalid value
BadValue(String),
/// invalid version format (should be x.y.z)
BadVersion,
/// the response is not an `ACK` (not an error)
/// (this is not actually an error, just a marker
/// to try to parse the response as some other type,
/// like a pair)
NotAck,
/// invalid pair
BadPair,
/// invalid error code in `ACK` response
BadCode,
/// invalid command position in `ACK` response
BadPos,
/// missing command position and/or error code in `ACK` response
NoCodePos,
/// missing error message in `ACK` response
NoMessage,
/// missing bitrate in audio format field
NoRate,
/// missing bits in audio format field
NoBits,
/// missing channels in audio format field
NoChans,
/// invalid bitrate in audio format field
BadRate(ParseIntError),
/// invalid bits in audio format field
BadBits(ParseIntError),
/// invalid channels in audio format field
BadChans(ParseIntError),
/// unknown state in state status field
BadState(String),
/// unknown error code in `ACK` response
BadErrorCode(usize),
}
impl StdError for ParseError {}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ParseError::*;
let desc = match *self {
BadInteger(_) => "invalid integer",
BadFloat(_) => "invalid float",
BadValue(_) => "invalid value",
BadVersion => "invalid version",
NotAck => "not an ACK",
BadPair => "invalid pair",
BadCode => "invalid code",
BadPos => "invalid position",
NoCodePos => "missing code and position",
NoMessage => "missing position",
NoRate => "missing audio format rate",
NoBits => "missing audio format bits",
NoChans => "missing audio format channels",
BadRate(_) => "invalid audio format rate",
BadBits(_) => "invalid audio format bits",
BadChans(_) => "invalid audio format channels",
BadState(_) => "invalid playing state",
BadErrorCode(_) => "unknown error code",
};
write!(f, "{}", desc)
}
}
impl From<ParseIntError> for ParseError {
fn from(e: ParseIntError) -> ParseError {
ParseError::BadInteger(e)
}
}
impl From<ParseFloatError> for ParseError {
fn from(e: ParseFloatError) -> ParseError {
ParseError::BadFloat(e)
}
}
impl From<StringParseError> for ParseError {
fn from(e: StringParseError) -> ParseError {
match e {}
}
}
// }}}
// Protocol errors {{{
/// Protocol errors
///
/// They usually occur when server violate expected command response format,
/// like missing fields in answer to some command, missing closing `OK`
/// line after data stream etc.
#[derive(Debug, Clone, PartialEq)]
pub enum ProtoError {
/// `OK` was expected, but it was missing
NotOk,
/// a data pair was expected
NotPair,
/// invalid handshake banner received
BadBanner,
/// expected some field, but it was missing
NoField(&'static str),
/// expected sticker value, but didn't find it
BadSticker,
}
impl StdError for ProtoError {}
impl fmt::Display for ProtoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let desc = match *self {
ProtoError::NotOk => "OK expected",
ProtoError::NotPair => "pair expected",
ProtoError::BadBanner => "banner error",
ProtoError::NoField(_) => "missing field",
ProtoError::BadSticker => "sticker error",
};
write!(f, "{}", desc)
}
}
// }}}