ferro-rs 0.2.15

A Laravel-inspired web framework for Rust
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Framework-wide error types
//!
//! Provides a unified error type that can be used throughout the framework
//! and automatically converts to appropriate HTTP responses.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use thiserror::Error;

/// Trait for errors that can be converted to HTTP responses
///
/// Implement this trait on your domain errors to customize the HTTP status code
/// and message that will be returned when the error is converted to a response.
///
/// # Example
///
/// ```rust,ignore
/// use ferro_rs::HttpError;
///
/// #[derive(Debug)]
/// struct UserNotFoundError { user_id: i32 }
///
/// impl std::fmt::Display for UserNotFoundError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         write!(f, "User {} not found", self.user_id)
///     }
/// }
///
/// impl std::error::Error for UserNotFoundError {}
///
/// impl HttpError for UserNotFoundError {
///     fn status_code(&self) -> u16 { 404 }
/// }
/// ```
pub trait HttpError: std::error::Error + Send + Sync + 'static {
    /// HTTP status code (default: 500)
    fn status_code(&self) -> u16 {
        500
    }

    /// Error message for HTTP response (default: error's Display)
    fn error_message(&self) -> String {
        self.to_string()
    }
}

/// Simple wrapper for creating one-off domain errors
///
/// Use this for inline/ad-hoc errors when you don't want to create
/// a dedicated error type.
///
/// # Example
///
/// ```rust,ignore
/// use ferro_rs::{AppError, FrameworkError};
///
/// pub async fn process() -> Result<(), FrameworkError> {
///     if invalid {
///         return Err(AppError::bad_request("Invalid input").into());
///     }
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct AppError {
    message: String,
    status_code: u16,
}

impl AppError {
    /// Create a new AppError with status 500 (Internal Server Error)
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            status_code: 500,
        }
    }

    /// Set the HTTP status code
    pub fn status(mut self, code: u16) -> Self {
        self.status_code = code;
        self
    }

    /// Create a 404 Not Found error
    pub fn not_found(message: impl Into<String>) -> Self {
        Self::new(message).status(404)
    }

    /// Create a 400 Bad Request error
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::new(message).status(400)
    }

    /// Create a 401 Unauthorized error
    pub fn unauthorized(message: impl Into<String>) -> Self {
        Self::new(message).status(401)
    }

    /// Create a 403 Forbidden error
    pub fn forbidden(message: impl Into<String>) -> Self {
        Self::new(message).status(403)
    }

    /// Create a 422 Unprocessable Entity error
    pub fn unprocessable(message: impl Into<String>) -> Self {
        Self::new(message).status(422)
    }

    /// Create a 409 Conflict error
    pub fn conflict(message: impl Into<String>) -> Self {
        Self::new(message).status(409)
    }
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

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

impl HttpError for AppError {
    fn status_code(&self) -> u16 {
        self.status_code
    }

    fn error_message(&self) -> String {
        self.message.clone()
    }
}

impl From<AppError> for FrameworkError {
    fn from(e: AppError) -> Self {
        FrameworkError::Domain {
            message: e.message,
            status_code: e.status_code,
        }
    }
}

/// Validation errors with Laravel/Inertia-compatible format
///
/// Contains a map of field names to error messages, supporting multiple
/// errors per field.
///
/// # Response Format
///
/// When converted to an HTTP response, produces Laravel-compatible JSON:
///
/// ```json
/// {
///     "message": "The given data was invalid.",
///     "errors": {
///         "email": ["The email field must be a valid email address."],
///         "password": ["The password field must be at least 8 characters."]
///     }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationErrors {
    /// Map of field names to their validation error messages
    #[serde(flatten)]
    pub errors: HashMap<String, Vec<String>>,
}

impl ValidationErrors {
    /// Create a new empty ValidationErrors
    pub fn new() -> Self {
        Self {
            errors: HashMap::new(),
        }
    }

    /// Add an error for a specific field
    pub fn add(&mut self, field: impl Into<String>, message: impl Into<String>) {
        self.errors
            .entry(field.into())
            .or_default()
            .push(message.into());
    }

    /// Check if there are any errors
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Convert from validator crate's ValidationErrors
    pub fn from_validator(errors: validator::ValidationErrors) -> Self {
        let mut result = Self::new();
        for (field, field_errors) in errors.field_errors() {
            for error in field_errors {
                let message = error
                    .message
                    .as_ref()
                    .map(|m| m.to_string())
                    .unwrap_or_else(|| format!("Validation failed for field '{field}'"));
                result.add(field.to_string(), message);
            }
        }
        result
    }

    /// Convert to JSON Value for response
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "message": "The given data was invalid.",
            "errors": self.errors
        })
    }
}

impl Default for ValidationErrors {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for ValidationErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Validation failed: {:?}", self.errors)
    }
}

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

/// Framework-wide error type
///
/// This enum represents all possible errors that can occur in the framework.
/// It implements `From<FrameworkError> for Response` so errors can be propagated
/// using the `?` operator in controller handlers.
///
/// # Example
///
/// ```rust,ignore
/// use ferro_rs::{App, FrameworkError, Response};
///
/// pub async fn index(_req: Request) -> Response {
///     let service = App::resolve::<MyService>()?;  // Returns FrameworkError on failure
///     // ...
/// }
/// ```
///
/// # Automatic Error Conversion
///
/// `FrameworkError` implements `From` for common error types, allowing seamless
/// use of the `?` operator:
///
/// ```rust,ignore
/// use ferro_rs::{DB, FrameworkError};
/// use sea_orm::ActiveModelTrait;
///
/// pub async fn create_todo() -> Result<Todo, FrameworkError> {
///     let todo = new_todo.insert(&*DB::get()?).await?;  // DbErr converts automatically!
///     Ok(todo)
/// }
/// ```
#[derive(Debug, Clone, Error)]
pub enum FrameworkError {
    /// Service not found in the dependency injection container
    #[error("Service '{type_name}' not registered in container")]
    ServiceNotFound {
        /// The type name of the service that was not found
        type_name: &'static str,
    },

    /// Parameter extraction failed (missing or invalid parameter)
    #[error("Missing required parameter: {param_name}")]
    ParamError {
        /// The name of the parameter that failed extraction
        param_name: String,
    },

    /// Validation error
    #[error("Validation error for '{field}': {message}")]
    ValidationError {
        /// The field that failed validation
        field: String,
        /// The validation error message
        message: String,
    },

    /// Database error
    #[error("Database error: {0}")]
    Database(String),

    /// Generic internal server error
    #[error("Internal server error: {message}")]
    Internal {
        /// The error message
        message: String,
    },

    /// Domain/application error with custom status code
    ///
    /// Used for user-defined domain errors that need custom HTTP status codes.
    #[error("{message}")]
    Domain {
        /// The error message
        message: String,
        /// HTTP status code
        status_code: u16,
    },

    /// Form validation errors (422 Unprocessable Entity)
    ///
    /// Contains multiple field validation errors in Laravel/Inertia format.
    #[error("Validation failed")]
    Validation(ValidationErrors),

    /// Authorization failed (403 Forbidden)
    ///
    /// Used when FormRequest::authorize() returns false.
    #[error("This action is unauthorized.")]
    Unauthorized,

    /// Model not found (404 Not Found)
    ///
    /// Used when route model binding fails to find the requested resource.
    #[error("{model_name} not found")]
    ModelNotFound {
        /// The name of the model that was not found
        model_name: String,
    },

    /// Parameter parse error (400 Bad Request)
    ///
    /// Used when a path parameter cannot be parsed to the expected type.
    #[error("Invalid parameter '{param}': expected {expected_type}")]
    ParamParse {
        /// The parameter value that failed to parse
        param: String,
        /// The expected type (e.g., "i32", "uuid")
        expected_type: &'static str,
    },
}

impl FrameworkError {
    /// Create a ServiceNotFound error for a given type
    pub fn service_not_found<T: ?Sized>() -> Self {
        Self::ServiceNotFound {
            type_name: std::any::type_name::<T>(),
        }
    }

    /// Create a ParamError for a missing parameter
    pub fn param(name: impl Into<String>) -> Self {
        Self::ParamError {
            param_name: name.into(),
        }
    }

    /// Create a ValidationError
    pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self::ValidationError {
            field: field.into(),
            message: message.into(),
        }
    }

    /// Create a DatabaseError
    pub fn database(message: impl Into<String>) -> Self {
        Self::Database(message.into())
    }

    /// Create an Internal error
    pub fn internal(message: impl Into<String>) -> Self {
        Self::Internal {
            message: message.into(),
        }
    }

    /// Create a Domain error with custom status code
    pub fn domain(message: impl Into<String>, status_code: u16) -> Self {
        Self::Domain {
            message: message.into(),
            status_code,
        }
    }

    /// Get the HTTP status code for this error
    pub fn status_code(&self) -> u16 {
        match self {
            Self::ServiceNotFound { .. } => 500,
            Self::ParamError { .. } => 400,
            Self::ValidationError { .. } => 422,
            Self::Database(_) => 500,
            Self::Internal { .. } => 500,
            Self::Domain { status_code, .. } => *status_code,
            Self::Validation(_) => 422,
            Self::Unauthorized => 403,
            Self::ModelNotFound { .. } => 404,
            Self::ParamParse { .. } => 400,
        }
    }

    /// Create a Validation error from ValidationErrors struct
    pub fn validation_errors(errors: ValidationErrors) -> Self {
        Self::Validation(errors)
    }

    /// Create a ModelNotFound error (404)
    pub fn model_not_found(name: impl Into<String>) -> Self {
        Self::ModelNotFound {
            model_name: name.into(),
        }
    }

    /// Create a ParamParse error (400)
    pub fn param_parse(param: impl Into<String>, expected_type: &'static str) -> Self {
        Self::ParamParse {
            param: param.into(),
            expected_type,
        }
    }

    /// Returns an actionable hint guiding the developer toward a fix.
    ///
    /// Hints are included in JSON error responses during development to help
    /// developers quickly resolve common issues. Variants with user-provided
    /// messages (Internal, Domain) or self-describing content (Validation,
    /// ValidationError) return `None`.
    pub fn hint(&self) -> Option<String> {
        match self {
            Self::ServiceNotFound { type_name } => Some(format!(
                "Register with App::bind::<{type_name}>() in your bootstrap.rs or a service provider"
            )),
            Self::ParamError { param_name } => Some(format!(
                "Check your route definition includes :{param_name} or verify the request body contains this field"
            )),
            Self::ModelNotFound { model_name } => Some(format!(
                "Verify the {model_name} exists in the database, or check that the route parameter matches a valid ID"
            )),
            Self::ParamParse {
                param,
                expected_type,
            } => Some(format!(
                "Route received '{param}' but expected a valid {expected_type}. Check the URL parameter format."
            )),
            Self::Database(_) => Some(
                "Check DATABASE_URL in .env and verify the database is running".to_string(),
            ),
            Self::Unauthorized => Some(
                "Check that the handler's form request authorize() returns true, or verify the user has the required permissions".to_string(),
            ),
            // No hints for user-provided or self-describing errors
            Self::Internal { .. } | Self::Domain { .. } | Self::ValidationError { .. } | Self::Validation(_) => None,
        }
    }
}

// Implement From<DbErr> for automatic error conversion with ?
impl From<sea_orm::DbErr> for FrameworkError {
    fn from(e: sea_orm::DbErr) -> Self {
        Self::Database(e.to_string())
    }
}

// Implement From<ferro_projections::Error> for automatic error conversion with ?
#[cfg(feature = "projections")]
impl From<ferro_projections::Error> for FrameworkError {
    fn from(e: ferro_projections::Error) -> Self {
        Self::Internal {
            message: e.to_string(),
        }
    }
}

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

    /// Helper: convert a FrameworkError to HttpResponse and parse its JSON body.
    fn error_to_json(err: FrameworkError) -> serde_json::Value {
        let resp: HttpResponse = err.into();
        serde_json::from_str(resp.body()).expect("response body should be valid JSON")
    }

    #[test]
    fn service_not_found_includes_hint() {
        let err = FrameworkError::service_not_found::<String>();
        let json = error_to_json(err);

        assert!(json.get("message").is_some(), "should have 'message' key");
        let hint = json
            .get("hint")
            .and_then(|v| v.as_str())
            .expect("should have 'hint' key");
        assert!(
            hint.contains("App::bind"),
            "hint should mention App::bind, got: {hint}"
        );
    }

    #[test]
    fn param_error_includes_hint() {
        let err = FrameworkError::param("user_id");
        let json = error_to_json(err);

        assert!(json.get("message").is_some());
        let hint = json
            .get("hint")
            .and_then(|v| v.as_str())
            .expect("should have hint");
        assert!(
            hint.contains(":user_id"),
            "hint should reference param name, got: {hint}"
        );
    }

    #[test]
    fn model_not_found_includes_hint() {
        let err = FrameworkError::model_not_found("User");
        let json = error_to_json(err);

        assert_eq!(json["message"], "User not found");
        let hint = json
            .get("hint")
            .and_then(|v| v.as_str())
            .expect("should have hint");
        assert!(hint.contains("User"), "hint should reference model name");
    }

    #[test]
    fn param_parse_includes_hint() {
        let err = FrameworkError::param_parse("abc", "i32");
        let json = error_to_json(err);

        let hint = json
            .get("hint")
            .and_then(|v| v.as_str())
            .expect("should have hint");
        assert!(hint.contains("abc"), "hint should include received value");
        assert!(hint.contains("i32"), "hint should include expected type");
    }

    #[test]
    fn database_error_includes_hint() {
        let err = FrameworkError::database("connection refused");
        let json = error_to_json(err);

        let hint = json
            .get("hint")
            .and_then(|v| v.as_str())
            .expect("should have hint");
        assert!(
            hint.contains("DATABASE_URL"),
            "hint should mention DATABASE_URL"
        );
    }

    #[test]
    fn unauthorized_includes_hint() {
        let err = FrameworkError::Unauthorized;
        let json = error_to_json(err);

        assert_eq!(json["message"], "This action is unauthorized.");
        let hint = json
            .get("hint")
            .and_then(|v| v.as_str())
            .expect("should have hint");
        assert!(
            hint.contains("authorize()"),
            "hint should mention authorize()"
        );
    }

    #[test]
    fn internal_error_has_no_hint() {
        let err = FrameworkError::internal("something broke");
        let json = error_to_json(err);

        assert!(json.get("message").is_some());
        assert!(
            json.get("hint").is_none(),
            "Internal errors should not have hints"
        );
    }

    #[test]
    fn domain_error_has_no_hint() {
        let err = FrameworkError::domain("custom message", 409);
        let json = error_to_json(err);

        assert_eq!(json["message"], "custom message");
        assert!(
            json.get("hint").is_none(),
            "Domain errors should not have hints"
        );
    }

    #[test]
    fn validation_errors_have_no_hint() {
        let mut errors = ValidationErrors::new();
        errors.add("email", "Email is required");
        let err = FrameworkError::validation_errors(errors);
        let json = error_to_json(err);

        assert!(
            json.get("hint").is_none(),
            "Validation errors should not have hints"
        );
        assert!(json.get("errors").is_some(), "should have errors field");
    }

    #[cfg(feature = "projections")]
    #[test]
    fn projection_error_converts_to_500() {
        let err = FrameworkError::from(ferro_projections::Error::Definition(
            "missing field".to_string(),
        ));
        assert_eq!(err.status_code(), 500);

        let json = error_to_json(err);
        let msg = json["message"].as_str().unwrap();
        assert!(
            msg.contains("missing field"),
            "error message should contain original text, got: {msg}"
        );
    }

    #[test]
    fn status_codes_are_correct() {
        assert_eq!(
            FrameworkError::service_not_found::<String>().status_code(),
            500
        );
        assert_eq!(FrameworkError::param("x").status_code(), 400);
        assert_eq!(FrameworkError::model_not_found("X").status_code(), 404);
        assert_eq!(FrameworkError::param_parse("x", "i32").status_code(), 400);
        assert_eq!(FrameworkError::database("err").status_code(), 500);
        assert_eq!(FrameworkError::internal("err").status_code(), 500);
        assert_eq!(FrameworkError::domain("err", 409).status_code(), 409);
        assert_eq!(FrameworkError::Unauthorized.status_code(), 403);
    }
}