Capturando Panics em Requisições
O Catch Panic é utilizado para capturar falhas que ocorrem durante o processamento de requisições pelo programa. Para a API específica, consulte a documentação.
Nota: Para usar CatchPanic
, é necessário habilitar o feature catch-panic
no Cargo.toml
:
salvo= { version = "xxx", features = ["catch-panic"] }
Introdução ao Middleware
CatchPanic
é um middleware que captura panics nos handlers. Quando ocorre um panic durante o processamento de uma requisição, ele captura esse panic e retorna um erro 500 Internal Server Error na resposta, em vez de fazer o servidor inteiro falhar.
Importante: Este middleware deve ser o primeiro a ser utilizado, para garantir que captura panics em outros middlewares ou handlers.
Uso Básico
use salvo_core::prelude::*;
use salvo_extra::catch_panic::CatchPanic;
#[handler]
async fn hello() {
panic!("erro de panic!");
}
#[tokio::main]
async fn main() {
let router = Router::new().hoop(CatchPanic::new()).get(hello);
let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
Server::new(acceptor).serve(router).await;
}
Comparação com Outros Frameworks para Entendimento Rápido
Axum
Equivalente ao middleware catch_panic
do Tower
no Axum:
use axum::{
Router,
routing::get,
http::StatusCode,
};
use tower::ServiceBuilder;
use tower_http::catch_panic::CatchPanicLayer;
async fn panic_handler() -> &'static str {
panic!("erro de panic!");
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(panic_handler))
.layer(
ServiceBuilder::new()
.layer(CatchPanicLayer::new())
);
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
Gin (Go)
No framework Gin da linguagem Go, o middleware equivalente é o Recovery:
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default() // Já inclui o middleware Recovery por padrão
r.GET("/", func(c *gin.Context) {
panic("erro de panic!")
})
r.Run(":8080")
}
Código de Exemplo
catch-panic/src/main.rs
use salvo::prelude::*;
// Handler that deliberately panics to demonstrate panic catching
#[handler]
async fn hello() {
panic!("panic error!");
}
#[tokio::main]
async fn main() {
// Initialize logging system
tracing_subscriber::fmt().init();
// Set up router with CatchPanic middleware to handle panics gracefully
// This prevents the server from crashing when a panic occurs in a handler
let router = Router::new().hoop(CatchPanic::new()).get(hello);
// Bind server to port 5800 and start serving
let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
Server::new(acceptor).serve(router).await;
}