Skip to main content

kasl_server/
error.rs

1//! One error shape for the whole API.
2//!
3//! kasl agents parse what comes back, so a failure has to be as predictable as
4//! a success: always JSON, always the same field. A handler returning a bare
5//! status leaves the agent guessing whether to retry, fix its payload, or tell
6//! the employee something is wrong.
7
8use axum::{
9    Json,
10    http::StatusCode,
11    response::{IntoResponse, Response},
12};
13use serde_json::json;
14
15/// A failed request, with the status the client should act on.
16#[derive(Debug)]
17pub struct ApiError {
18    status: StatusCode,
19    message: String,
20}
21
22impl ApiError {
23    pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
24        Self {
25            status,
26            message: message.into(),
27        }
28    }
29
30    /// The payload was understood but is not acceptable - the agent must fix
31    /// it rather than retry.
32    pub fn bad_request(message: impl Into<String>) -> Self {
33        Self::new(StatusCode::BAD_REQUEST, message)
34    }
35}
36
37impl std::fmt::Display for ApiError {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.write_str(&self.message)
40    }
41}
42
43impl IntoResponse for ApiError {
44    fn into_response(self) -> Response {
45        // Server-side faults are logged in full and reported in outline: an
46        // agent has no use for a database error, and the message could carry
47        // details of someone else's data.
48        if self.status.is_server_error() {
49            tracing::error!(status = %self.status, error = %self.message, "request failed");
50            return (self.status, Json(json!({ "error": "internal server error" }))).into_response();
51        }
52
53        (self.status, Json(json!({ "error": self.message }))).into_response()
54    }
55}
56
57impl From<sqlx::Error> for ApiError {
58    fn from(error: sqlx::Error) -> Self {
59        Self::new(StatusCode::INTERNAL_SERVER_ERROR, error.to_string())
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use axum::body::to_bytes;
67
68    async fn body_of(error: ApiError) -> serde_json::Value {
69        let response = error.into_response();
70        let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
71        serde_json::from_slice(&bytes).unwrap()
72    }
73
74    #[tokio::test]
75    async fn client_errors_explain_themselves() {
76        let body = body_of(ApiError::bad_request("date is not a calendar date")).await;
77        assert_eq!(body["error"], "date is not a calendar date");
78    }
79
80    #[tokio::test]
81    async fn server_errors_do_not_leak_their_cause() {
82        let body = body_of(ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "relation \"users\" does not exist")).await;
83        assert_eq!(body["error"], "internal server error", "internals must not reach the client");
84    }
85
86    #[test]
87    fn the_status_survives_into_the_response() {
88        let response = ApiError::new(StatusCode::UNAUTHORIZED, "nope").into_response();
89        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
90    }
91}