expression

REST: map domain failures to safe public errors

Convert domain failures into deliberate HTTP responses at the boundary. Not every internal diagnostic belongs in an error body. The demonstration uses about:blank for a generic internal failure, with no private information; real services also need protected diagnostics and correlation. Standalone synthetic example. Expected stdout (not executed): 500 Internal Server Error Common mistake: Echoing database errors or secrets to clients.

Formal Syntax & Structure

rust syntaxrust
impl IntoResponse for ApiError

Working Example

Example Snippetrust
use axum::{Router, Json, body::{Body, to_bytes}, http::{Request, StatusCode}};use serde::{Deserialize, Serialize};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::response::{IntoResponse, Response};    struct ApiError;    impl IntoResponse for ApiError {        fn into_response(self) -> Response {            (StatusCode::INTERNAL_SERVER_ERROR,             [("content-type", "application/problem+json")],             Json(serde_json::json!({"type":"about:blank","title":"Internal Server Error","status":500}))).into_response()        }    }    let res = ApiError.into_response();    let status = res.status();    let value: serde_json::Value = serde_json::from_slice(&to_bytes(res.into_body(), 1024).await.unwrap()).unwrap();    println!("{} {}", status.as_u16(), value["title"].as_str().unwrap());}
Rust Reference