typestar

Un tipo de error que responde en Rust

Implementa IntoResponse para tu error y los handlers pueden usar el operador ?.

use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{routing::get, Json, Router};
use serde_json::json;

enum ApiError {
    NotFound(String),
    Invalid { field: &'static str },
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            ApiError::NotFound(what) => {
                (StatusCode::NOT_FOUND, format!("no such {what}"))
            }
            ApiError::Invalid { field } => (
                StatusCode::UNPROCESSABLE_ENTITY,
                format!("{field} is invalid"),
            ),
        };
        (status, Json(json!({"error": message}))).into_response()
    }
}

async fn tour() -> Result<String, ApiError> {
    Err(ApiError::NotFound("tour".to_string()))
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/tours/none", get(tour));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Cómo funciona

  1. Cada variante se mapea a un código de estado y un mensaje.
  2. IntoResponse es lo que lo vuelve retornable.
  3. Los handlers se leen entonces como funciones falibles comunes.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
37
Caracteres a escribir
872
Tokens
247
Ritmo de tres estrellas
110 tpm

Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 135 segundos.

Escribe este fragmento

Paso 2 de 3 en Respuestas y middleware; paso 7 de 9 en Servicios web con axum.

← Anterior Siguiente →