ultimo 0.9.0

Modern Rust web framework with automatic TypeScript client generation
Documentation
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Error handling system for Ultimo
//!
//! Provides comprehensive error types that automatically convert to proper HTTP responses
//! with structured JSON error messages.

use serde::Serialize;
use std::fmt;

/// Main error type for Ultimo framework
#[derive(Debug)]
pub enum UltimoError {
    /// HTTP error with status code and message
    Http { status: u16, message: String },
    /// Validation error with field-level details
    Validation {
        message: String,
        details: Vec<ValidationError>,
    },
    /// Authentication error (401)
    Unauthorized(String),
    /// Authorization error (403)
    Forbidden(String),
    /// Not found error (404)
    NotFound(String),
    /// Internal server error (500)
    Internal(String),
    /// Bad request error (400)
    BadRequest(String),
    /// Hyper-specific errors
    Hyper(hyper::Error),
    /// HTTP errors
    HttpError(hyper::http::Error),
    /// JSON serialization/deserialization errors
    Json(serde_json::Error),
    /// IO errors
    Io(std::io::Error),
}

/// Field-level validation error
#[derive(Debug, Clone, Serialize)]
pub struct ValidationError {
    pub field: String,
    pub message: String,
}

/// Standard error response format
#[derive(Debug, Serialize)]
pub struct ErrorResponse {
    pub error: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Vec<ValidationError>>,
}

impl UltimoError {
    /// Get HTTP status code for this error
    pub fn status_code(&self) -> u16 {
        match self {
            UltimoError::Http { status, .. } => *status,
            UltimoError::Validation { .. } => 422,
            UltimoError::Unauthorized(_) => 401,
            UltimoError::Forbidden(_) => 403,
            UltimoError::NotFound(_) => 404,
            UltimoError::BadRequest(_) => 400,
            UltimoError::Internal(_) => 500,
            UltimoError::Hyper(_) => 500,
            UltimoError::HttpError(_) => 500,
            UltimoError::Json(_) => 400,
            UltimoError::Io(_) => 500,
        }
    }

    /// Convert error to JSON response body
    pub fn to_error_response(&self) -> ErrorResponse {
        match self {
            UltimoError::Http { message, .. } => ErrorResponse {
                error: "HttpError".to_string(),
                message: message.clone(),
                details: None,
            },
            UltimoError::Validation { message, details } => ErrorResponse {
                error: "ValidationError".to_string(),
                message: message.clone(),
                details: Some(details.clone()),
            },
            UltimoError::Unauthorized(msg) => ErrorResponse {
                error: "Unauthorized".to_string(),
                message: msg.clone(),
                details: None,
            },
            UltimoError::Forbidden(msg) => ErrorResponse {
                error: "Forbidden".to_string(),
                message: msg.clone(),
                details: None,
            },
            UltimoError::NotFound(msg) => ErrorResponse {
                error: "NotFound".to_string(),
                message: msg.clone(),
                details: None,
            },
            UltimoError::BadRequest(msg) => ErrorResponse {
                error: "BadRequest".to_string(),
                message: msg.clone(),
                details: None,
            },
            UltimoError::Internal(msg) => ErrorResponse {
                error: "InternalError".to_string(),
                message: msg.clone(),
                details: None,
            },
            // Hyper/HttpError/Io are internal-machinery errors (protocol
            // internals, filesystem paths, OS error text) — never echo their
            // `Display` text to the client. Full detail is still available
            // to the app via `Display`/`Debug` for server-side logging.
            UltimoError::Hyper(_) => ErrorResponse {
                error: "ServerError".to_string(),
                message: "internal server error".to_string(),
                details: None,
            },
            UltimoError::HttpError(_) => ErrorResponse {
                error: "ServerError".to_string(),
                message: "internal server error".to_string(),
                details: None,
            },
            // JSON errors originate from the client's own malformed request
            // body, so the parser's position/message is safe (and useful) to
            // return as-is.
            UltimoError::Json(err) => ErrorResponse {
                error: "JsonError".to_string(),
                message: format!("JSON parsing error: {}", err),
                details: None,
            },
            UltimoError::Io(_) => ErrorResponse {
                error: "IoError".to_string(),
                message: "internal server error".to_string(),
                details: None,
            },
        }
    }
}

impl fmt::Display for UltimoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UltimoError::Http { status, message } => {
                write!(f, "HTTP {}: {}", status, message)
            }
            UltimoError::Validation { message, .. } => write!(f, "Validation error: {}", message),
            UltimoError::Unauthorized(msg) => write!(f, "Unauthorized: {}", msg),
            UltimoError::Forbidden(msg) => write!(f, "Forbidden: {}", msg),
            UltimoError::NotFound(msg) => write!(f, "Not found: {}", msg),
            UltimoError::BadRequest(msg) => write!(f, "Bad request: {}", msg),
            UltimoError::Internal(msg) => write!(f, "Internal error: {}", msg),
            UltimoError::Hyper(err) => write!(f, "Hyper error: {}", err),
            UltimoError::HttpError(err) => write!(f, "HTTP error: {}", err),
            UltimoError::Json(err) => write!(f, "JSON error: {}", err),
            UltimoError::Io(err) => write!(f, "IO error: {}", err),
        }
    }
}

impl std::error::Error for UltimoError {}

// Conversions from common error types
impl From<hyper::Error> for UltimoError {
    fn from(err: hyper::Error) -> Self {
        UltimoError::Hyper(err)
    }
}

impl From<hyper::http::Error> for UltimoError {
    fn from(err: hyper::http::Error) -> Self {
        UltimoError::HttpError(err)
    }
}

impl From<serde_json::Error> for UltimoError {
    fn from(err: serde_json::Error) -> Self {
        UltimoError::Json(err)
    }
}

impl From<std::io::Error> for UltimoError {
    fn from(err: std::io::Error) -> Self {
        UltimoError::Io(err)
    }
}

/// Result type alias for Ultimo operations
pub type Result<T> = std::result::Result<T, UltimoError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_status_codes() {
        assert_eq!(UltimoError::Unauthorized("test".into()).status_code(), 401);
        assert_eq!(UltimoError::Forbidden("test".into()).status_code(), 403);
        assert_eq!(UltimoError::NotFound("test".into()).status_code(), 404);
        assert_eq!(UltimoError::BadRequest("test".into()).status_code(), 400);
        assert_eq!(UltimoError::Internal("test".into()).status_code(), 500);
    }

    #[test]
    fn test_error_response_format() {
        let err = UltimoError::Validation {
            message: "Invalid input".to_string(),
            details: vec![ValidationError {
                field: "email".to_string(),
                message: "Invalid email format".to_string(),
            }],
        };

        let response = err.to_error_response();
        assert_eq!(response.error, "ValidationError");
        assert_eq!(response.message, "Invalid input");
        assert!(response.details.is_some());
        assert_eq!(response.details.unwrap().len(), 1);
    }

    #[test]
    fn test_http_error_status_code() {
        let err = UltimoError::Http {
            status: 418,
            message: "I'm a teapot".to_string(),
        };
        assert_eq!(err.status_code(), 418);
    }

    #[test]
    fn test_validation_error_status_code() {
        let err = UltimoError::Validation {
            message: "Validation failed".to_string(),
            details: vec![],
        };
        assert_eq!(err.status_code(), 422);
    }

    #[test]
    fn test_error_conversions() {
        // Test JSON error conversion
        let json_err = serde_json::from_str::<serde_json::Value>("invalid json");
        assert!(json_err.is_err());
        let ultimo_err = UltimoError::from(json_err.unwrap_err());
        assert_eq!(ultimo_err.status_code(), 400);

        // Test IO error conversion
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let ultimo_err = UltimoError::from(io_err);
        assert_eq!(ultimo_err.status_code(), 500);
    }

    #[test]
    fn test_error_display_formatting() {
        let err = UltimoError::NotFound("User not found".to_string());
        assert_eq!(format!("{}", err), "Not found: User not found");

        let err = UltimoError::Unauthorized("Invalid token".to_string());
        assert_eq!(format!("{}", err), "Unauthorized: Invalid token");

        let err = UltimoError::Http {
            status: 503,
            message: "Service unavailable".to_string(),
        };
        assert_eq!(format!("{}", err), "HTTP 503: Service unavailable");
    }

    #[test]
    fn test_all_error_response_types() {
        // Test Http error response
        let err = UltimoError::Http {
            status: 500,
            message: "Server error".to_string(),
        };
        let response = err.to_error_response();
        assert_eq!(response.error, "HttpError");
        assert_eq!(response.message, "Server error");

        // Test Unauthorized error response
        let err = UltimoError::Unauthorized("No token".to_string());
        let response = err.to_error_response();
        assert_eq!(response.error, "Unauthorized");
        assert_eq!(response.message, "No token");

        // Test Forbidden error response
        let err = UltimoError::Forbidden("Access denied".to_string());
        let response = err.to_error_response();
        assert_eq!(response.error, "Forbidden");
        assert_eq!(response.message, "Access denied");

        // Test NotFound error response
        let err = UltimoError::NotFound("Resource not found".to_string());
        let response = err.to_error_response();
        assert_eq!(response.error, "NotFound");
        assert_eq!(response.message, "Resource not found");

        // Test BadRequest error response
        let err = UltimoError::BadRequest("Invalid data".to_string());
        let response = err.to_error_response();
        assert_eq!(response.error, "BadRequest");
        assert_eq!(response.message, "Invalid data");

        // Test Internal error response
        let err = UltimoError::Internal("Database failure".to_string());
        let response = err.to_error_response();
        assert_eq!(response.error, "InternalError");
        assert_eq!(response.message, "Database failure");
    }

    #[test]
    fn test_validation_error_with_multiple_fields() {
        let err = UltimoError::Validation {
            message: "Multiple validation errors".to_string(),
            details: vec![
                ValidationError {
                    field: "email".to_string(),
                    message: "Invalid format".to_string(),
                },
                ValidationError {
                    field: "password".to_string(),
                    message: "Too short".to_string(),
                },
            ],
        };

        let response = err.to_error_response();
        assert_eq!(response.error, "ValidationError");
        let details = response.details.unwrap();
        assert_eq!(details.len(), 2);
        assert_eq!(details[0].field, "email");
        assert_eq!(details[1].field, "password");
    }

    #[test]
    fn test_json_error_conversion_and_response() {
        let json_err = serde_json::from_str::<serde_json::Value>("not valid json");
        let ultimo_err = UltimoError::from(json_err.unwrap_err());
        let response = ultimo_err.to_error_response();

        assert_eq!(response.error, "JsonError");
        assert!(response.message.contains("JSON parsing error"));
        assert!(response.details.is_none());
    }

    #[test]
    fn test_io_error_conversion_and_response() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
        let ultimo_err = UltimoError::from(io_err);
        let response = ultimo_err.to_error_response();

        assert_eq!(response.error, "IoError");
        // Client-facing message must be generic — the underlying OS error
        // text (which can include filesystem paths) must never reach the
        // client. Full detail remains available via `Display` for logging.
        assert_eq!(response.message, "internal server error");
        assert!(!response.message.contains("access denied"));
        assert!(response.details.is_none());
    }

    #[test]
    fn test_http_error_does_not_leak_details() {
        // An invalid header name makes `.body()` return a real
        // hyper::http::Error to convert from.
        let http_err = hyper::Response::builder()
            .header("bad header name", "value")
            .body(())
            .expect_err("a header name with a space is invalid and must fail to build");
        let ultimo_err = UltimoError::from(http_err);
        let response = ultimo_err.to_error_response();
        assert_eq!(response.error, "ServerError");
        assert_eq!(response.message, "internal server error");
    }

    #[test]
    fn test_error_response_serialization() {
        let response = ErrorResponse {
            error: "TestError".to_string(),
            message: "Test message".to_string(),
            details: None,
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("TestError"));
        assert!(json.contains("Test message"));
    }

    #[test]
    fn test_validation_error_serialization() {
        let validation_err = ValidationError {
            field: "username".to_string(),
            message: "Required field".to_string(),
        };

        let json = serde_json::to_string(&validation_err).unwrap();
        assert!(json.contains("username"));
        assert!(json.contains("Required field"));
    }

    #[test]
    fn test_error_is_send_sync() {
        fn assert_send<T: Send>() {}

        // UltimoError should be Send but not necessarily Sync
        assert_send::<UltimoError>();
    }
}