salvo_core 0.91.1

Salvo is a powerful web framework that can make your work easier.
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
//! Error catching and custom error page handling.
//!
//! When a [`Response`] has an error status code (4xx or 5xx) and an empty body,
//! Salvo uses a `Catcher` to generate a user-friendly error page.
//!
//! # Overview
//!
//! The catcher system provides:
//!
//! - **Default error pages** in multiple formats (HTML, JSON, XML, Plain text)
//! - **Custom error handlers** for specific status codes or error types
//! - **Middleware-style chaining** of error handlers
//! - **Content negotiation** based on the `Accept` header
//!
//! # Basic Usage
//!
//! Add a default catcher to your service:
//!
//! ```ignore
//! use salvo_core::prelude::*;
//!
//! let service = Service::new(router).catcher(Catcher::default());
//! ```
//!
//! # Custom Error Handlers
//!
//! Create custom handlers for specific errors:
//!
//! ```
//! use salvo_core::catcher::Catcher;
//! use salvo_core::prelude::*;
//!
//! #[handler]
//! async fn handle404(&self, res: &mut Response, ctrl: &mut FlowCtrl) {
//!     if let Some(StatusCode::NOT_FOUND) = res.status_code {
//!         res.render("Custom 404 Error Page");
//!         ctrl.skip_rest(); // Skip remaining handlers
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     Service::new(Router::new()).catcher(Catcher::default().hoop(handle404));
//! }
//! ```
//!
//! # Multiple Error Handlers
//!
//! Chain multiple handlers for different error types:
//!
//! ```ignore
//! let catcher = Catcher::default()
//!     .hoop(handle404)
//!     .hoop(handle500)
//!     .hoop(handle_api_errors);
//! ```
//!
//! Handlers are called in order. Use [`FlowCtrl::skip_rest()`] to stop processing.
//!
//! # Response Formats
//!
//! The default [`Catcher`] supports sending error pages in multiple formats
//! based on the request's `Accept` header:
//!
//! | Accept Header | Response Format |
//! |---------------|-----------------|
//! | `text/html` | HTML page with styling |
//! | `application/json` | JSON object |
//! | `application/xml` | XML document |
//! | `text/plain` | Plain text |
//!
//! # Environment Variables
//!
//! Control error detail visibility with `SALVO_STATUS_ERROR`:
//!
//! ```sh
//! # Show full details (not recommended for production)
//! SALVO_STATUS_ERROR=force_detail,force_cause
//!
//! # Show details only in debug builds
//! SALVO_STATUS_ERROR=debug_detail,debug_cause
//!
//! # Never show details (secure default)
//! SALVO_STATUS_ERROR=never_detail,never_cause
//! ```
//!
//! Options:
//! - `force_detail` / `debug_detail` / `never_detail`: Control error detail visibility
//! - `force_cause` / `debug_cause` / `never_cause`: Control error cause visibility

use std::borrow::Cow;
use std::collections::HashSet;
use std::env;
use std::fmt::{self, Debug, Formatter};
use std::sync::{Arc, LazyLock};

use async_trait::async_trait;
use bytes::Bytes;
use mime::Mime;
use serde::Serialize;

use crate::handler::{Handler, WhenHoop};
use crate::http::mime::guess_accept_mime;
use crate::http::{Request, ResBody, Response, StatusCode, StatusError, header};
use crate::{Depot, FlowCtrl};

static SUPPORTED_FORMATS: LazyLock<Vec<mime::Name>> =
    LazyLock::new(|| vec![mime::JSON, mime::HTML, mime::XML, mime::PLAIN]);
static STATUS_ERROR_SETS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    HashSet::from([
        "force_detail",
        "debug_detail",
        "never_detail",
        "force_cause",
        "debug_cause",
        "never_cause",
    ])
});

/// Cached parsed `SALVO_STATUS_ERROR` environment variable options.
static PARSED_ENV_SETS: LazyLock<HashSet<String>> = LazyLock::new(|| {
    env::var("SALVO_STATUS_ERROR")
        .unwrap_or_default()
        .split(',')
        .filter_map(|s| {
            let s = s.trim().to_lowercase();
            if STATUS_ERROR_SETS.contains(s.as_str()) {
                Some(s)
            } else if s.is_empty() {
                None
            } else {
                tracing::warn!("unknown SALVO_STATUS_ERROR option: {}", s);
                None
            }
        })
        .collect::<HashSet<_>>()
});
const SALVO_LINK: &str = r#"<a href="https://salvo.rs" target="_blank">salvo</a>"#;

/// `Catcher` is used to catch errors.
///
/// View [module level documentation](index.html) for more details.
pub struct Catcher {
    goal: Arc<dyn Handler>,
    hoops: Vec<Arc<dyn Handler>>,
}
impl Default for Catcher {
    /// Create new `Catcher` with its goal handler is [`DefaultGoal`].
    fn default() -> Self {
        Self {
            goal: Arc::new(DefaultGoal::new()),
            hoops: vec![],
        }
    }
}
impl Debug for Catcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Catcher").finish()
    }
}
impl Catcher {
    /// Create new `Catcher`.
    pub fn new<H: Handler>(goal: H) -> Self {
        Self {
            goal: Arc::new(goal),
            hoops: vec![],
        }
    }

    /// Get current catcher's middlewares reference.
    #[inline]
    #[must_use]
    pub fn hoops(&self) -> &Vec<Arc<dyn Handler>> {
        &self.hoops
    }
    /// Get current catcher's middlewares mutable reference.
    #[inline]
    pub fn hoops_mut(&mut self) -> &mut Vec<Arc<dyn Handler>> {
        &mut self.hoops
    }

    /// Add a handler as middleware, it will run the handler when error caught.
    #[inline]
    #[must_use]
    pub fn hoop<H: Handler>(mut self, hoop: H) -> Self {
        self.hoops.push(Arc::new(hoop));
        self
    }

    /// Add a handler as middleware, it will run the handler when error caught.
    ///
    /// This middleware is only effective when the filter returns true..
    #[inline]
    #[must_use]
    pub fn hoop_when<H, F>(mut self, hoop: H, filter: F) -> Self
    where
        H: Handler,
        F: Fn(&Request, &Depot) -> bool + Send + Sync + 'static,
    {
        self.hoops.push(Arc::new(WhenHoop {
            inner: hoop,
            filter,
        }));
        self
    }

    /// Catch error and send error page.
    pub async fn catch(&self, req: &mut Request, depot: &mut Depot, res: &mut Response) {
        let mut ctrl = FlowCtrl::new(self.hoops.iter().chain([&self.goal]).cloned().collect());
        ctrl.call_next(req, depot, res).await;
    }
}

/// Default [`Handler`] used as goal for [`Catcher`].
///
/// If http status is error, and all custom handlers is not catch it and write body,
/// `DefaultGoal` will used to catch them.
///
/// `DefaultGoal` supports sending error pages in `XML`, `JSON`, `HTML`, `Text` formats.
#[derive(Default, Debug)]
pub struct DefaultGoal {
    footer: Option<Cow<'static, str>>,
}
impl DefaultGoal {
    /// Create new `DefaultGoal`.
    #[must_use]
    pub fn new() -> Self {
        Self { footer: None }
    }
    /// Create new `DefaultGoal` with custom footer.
    #[inline]
    #[must_use]
    pub fn with_footer(footer: impl Into<Cow<'static, str>>) -> Self {
        Self::new().footer(footer)
    }

    /// Set custom footer which is only used in html error page.
    ///
    /// If footer is `None`, then use default footer.
    /// Default footer is `<a href="https://salvo.rs" target="_blank">salvo</a>`.
    #[must_use]
    pub fn footer(mut self, footer: impl Into<Cow<'static, str>>) -> Self {
        self.footer = Some(footer.into());
        self
    }
}
#[async_trait]
impl Handler for DefaultGoal {
    async fn handle(
        &self,
        req: &mut Request,
        _depot: &mut Depot,
        res: &mut Response,
        _ctrl: &mut FlowCtrl,
    ) {
        let status = res.status_code.unwrap_or(StatusCode::NOT_FOUND);
        if (status.is_server_error() || status.is_client_error())
            && (res.body.is_none() || res.body.is_error())
        {
            write_error_default(req, res, self.footer.as_deref());
        }
    }
}

fn status_error_html(
    code: StatusCode,
    name: &str,
    brief: &str,
    detail: Option<&str>,
    cause: Option<&str>,
    footer: Option<&str>,
) -> String {
    format!(
        r#"<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>{0}: {1}</title>
    <style>
    :root {{
        --bg-color: #fff;
        --text-color: #222;
    }}
    body {{
        background: var(--bg-color);
        color: var(--text-color);
        text-align: center;
    }}
    pre {{ text-align: left; padding: 0 1rem; }}
    footer{{text-align:center;}}
    @media (prefers-color-scheme: dark) {{
        :root {{
            --bg-color: #222;
            --text-color: #ddd;
        }}
        a:link {{ color: red; }}
        a:visited {{ color: #a8aeff; }}
        a:hover {{color: #a8aeff;}}
        a:active {{color: #a8aeff;}}
    }}
    </style>
</head>
<body>
    <div><h1>{}: {}</h1><h3>{}</h3>{}{}<hr><footer>{}</footer></div>
</body>
</html>"#,
        code.as_u16(),
        name,
        brief,
        detail
            .map(|detail| format!("<pre>{detail}</pre>"))
            .unwrap_or_default(),
        cause
            .map(|cause| format!("<pre>{cause:#?}</pre>"))
            .unwrap_or_default(),
        footer.unwrap_or(SALVO_LINK)
    )
}

#[inline]
fn status_error_json(
    code: StatusCode,
    name: &str,
    brief: &str,
    detail: Option<&str>,
    cause: Option<&str>,
) -> String {
    #[derive(Serialize)]
    struct Data<'a> {
        error: Error<'a>,
    }
    #[derive(Serialize)]
    struct Error<'a> {
        code: u16,
        name: &'a str,
        brief: &'a str,
        #[serde(skip_serializing_if = "Option::is_none")]
        detail: Option<&'a str>,
        #[serde(skip_serializing_if = "Option::is_none")]
        cause: Option<&'a str>,
    }
    let data = Data {
        error: Error {
            code: code.as_u16(),
            name,
            brief,
            detail,
            cause,
        },
    };
    serde_json::to_string(&data).unwrap_or_default()
}

fn status_error_plain(
    code: StatusCode,
    name: &str,
    brief: &str,
    detail: Option<&str>,
    cause: Option<&str>,
) -> String {
    format!(
        "code: {}\n\nname: {}\n\nbrief: {}{}{}",
        code.as_u16(),
        name,
        brief,
        detail
            .map(|detail| format!("\n\ndetail: {detail}"))
            .unwrap_or_default(),
        cause
            .map(|cause| format!("\n\ncause: {cause:#?}"))
            .unwrap_or_default(),
    )
}

fn status_error_xml(
    code: StatusCode,
    name: &str,
    brief: &str,
    detail: Option<&str>,
    cause: Option<&str>,
) -> String {
    #[derive(Serialize)]
    struct Data<'a> {
        code: u16,
        name: &'a str,
        brief: &'a str,
        #[serde(skip_serializing_if = "Option::is_none")]
        detail: Option<&'a str>,
        #[serde(skip_serializing_if = "Option::is_none")]
        cause: Option<&'a str>,
    }

    let data = Data {
        code: code.as_u16(),
        name,
        brief,
        detail,
        cause,
    };
    serde_xml_rs::to_string(&data).unwrap_or_default()
}

/// Create bytes from `StatusError`.
///
/// You can use environment variable `SALVO_STATUS_ERROR` to control whether to
/// show `detail` and `cause` information in default error page.
///
/// force_detail: always show detail information in error page even in release mode.
/// debug_detail: only show detail information in error page in debug mode.
/// never_detail: never show detail information in error page.
///
/// force_cause: always show cause information in error page even in release mode.
/// debug_cause: only show cause information in error page in debug mode.
/// never_cause: never show detail information in error page.
///
/// For example:
///
/// ```sh
/// SALVO_STATUS_ERROR=force_cause,force_detail
/// ```
/// will always show `detail` and `cause` information in error page even in release mode.
///
/// If `SALVO_STATUS_ERROR` is not set, then `detail` and `cause` will only be
/// shown in error page in debug mode for security reason.
#[doc(hidden)]
#[inline]
pub fn status_error_bytes(
    err: &StatusError,
    prefer_format: &Mime,
    footer: Option<&str>,
) -> (Mime, Bytes) {
    let format = if !SUPPORTED_FORMATS.contains(&prefer_format.subtype()) {
        mime::TEXT_HTML
    } else {
        prefer_format.clone()
    };

    let env_sets = &*PARSED_ENV_SETS;

    let detail = if !env_sets.contains("never_detail")
        && (env_sets.contains("force_detail")
            || (env_sets.contains("debug_detail") && cfg!(debug_assertions)))
    {
        err.detail.as_deref()
    } else {
        None
    };

    let cause = if !env_sets.contains("never_cause")
        && (env_sets.contains("force_cause")
            || (env_sets.contains("debug_cause") && cfg!(debug_assertions)))
    {
        err.cause.as_ref().map(|e| format!("{e:#?}"))
    } else {
        None
    };

    let content = match format.subtype().as_ref() {
        "plain" => status_error_plain(err.code, &err.name, &err.brief, detail, cause.as_deref()),
        "json" => status_error_json(err.code, &err.name, &err.brief, detail, cause.as_deref()),
        "xml" => status_error_xml(err.code, &err.name, &err.brief, detail, cause.as_deref()),
        _ => status_error_html(
            err.code,
            &err.name,
            &err.brief,
            detail,
            cause.as_deref(),
            footer,
        ),
    };
    (format, Bytes::from(content))
}

#[doc(hidden)]
pub fn write_error_default(req: &Request, res: &mut Response, footer: Option<&str>) {
    let format = guess_accept_mime(req, None);
    let (format, data) = if let ResBody::Error(body) = &res.body {
        status_error_bytes(body, &format, footer)
    } else {
        let status = res.status_code.unwrap_or(StatusCode::NOT_FOUND);
        status_error_bytes(
            &StatusError::from_code(status).unwrap_or_else(StatusError::internal_server_error),
            &format,
            footer,
        )
    };
    res.headers_mut().insert(
        header::CONTENT_TYPE,
        format.to_string().parse().expect("invalid `Content-Type`"),
    );
    let _ = res.write_body(data);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prelude::*;
    use crate::test::{ResponseExt, TestClient};

    struct CustomError;
    #[async_trait]
    impl Writer for CustomError {
        async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
            res.status_code = Some(StatusCode::INTERNAL_SERVER_ERROR);
            res.render("custom error");
        }
    }

    #[handler]
    async fn handle404(
        &self,
        _req: &Request,
        _depot: &Depot,
        res: &mut Response,
        ctrl: &mut FlowCtrl,
    ) {
        if res.status_code.is_none() || Some(StatusCode::NOT_FOUND) == res.status_code {
            res.render("Custom 404 Error Page");
            ctrl.skip_rest();
        }
    }

    #[tokio::test]
    async fn test_handle_error() {
        #[handler]
        async fn handle_custom() -> Result<(), CustomError> {
            Err(CustomError)
        }
        let router = Router::new().push(Router::with_path("custom").get(handle_custom));
        let service = Service::new(router);

        async fn access(service: &Service, name: &str) -> String {
            TestClient::get(format!("http://127.0.0.1:8698/{name}"))
                .send(service)
                .await
                .take_string()
                .await
                .unwrap()
        }

        assert_eq!(access(&service, "custom").await, "custom error");
    }

    #[tokio::test]
    async fn test_custom_catcher() {
        #[handler]
        async fn hello() -> &'static str {
            "Hello World"
        }
        let router = Router::new().get(hello);
        let service = Service::new(router).catcher(Catcher::default().hoop(handle404));

        async fn access(service: &Service, name: &str) -> String {
            TestClient::get(format!("http://127.0.0.1:8698/{name}"))
                .send(service)
                .await
                .take_string()
                .await
                .unwrap()
        }

        assert_eq!(access(&service, "notfound").await, "Custom 404 Error Page");
    }
}