Skip to main content

ash_jsonapi/
error.rs

1//! JSON:API error objects and their mapping onto HTTP status codes.
2//!
3//! Every error a handler returns is one of these: a code, the HTTP status it
4//! maps to, and a pointer at whatever caused it. Internal errors are
5//! sanitized — the detail is dropped and only the correlation id survives, so
6//! a connection string in a data-layer error cannot reach a client.
7
8use crate::context::Context;
9use crate::document::{ErrorObject, ErrorSource};
10pub use http_types::StatusCode;
11
12/// The JSON:API `code` values this crate emits, and the HTTP status each
13/// carries.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ErrorCode {
16    /// `UnknownResource` / `UnknownAction` / `NotFound`.
17    NotFound,
18    /// A deliberate policy denial.
19    Forbidden,
20    /// A policy *outage* — distinct from a denial, and retriable.
21    PolicyUnavailable,
22    MissingTenant,
23    /// A validation failure on a specific attribute.
24    InvalidAttribute,
25    /// A malformed or unknown query parameter — an unknown sort attribute,
26    /// filter key or include path, or two pagination strategies at once.
27    /// Resolved against the schema before the data layer is touched.
28    InvalidParameter,
29    /// Optimistic-concurrency failure; retriable.
30    Conflict,
31    /// The `If-Match` precondition was supplied and stale.
32    PreconditionFailed,
33    LockContention,
34    /// The domain is draining. A lifecycle signal, not a fault.
35    Closing,
36    Unsupported,
37    /// The request body was not sent as `application/vnd.api+json`.
38    ///
39    /// JSON:API requires the media type on any request carrying a document,
40    /// and requires `415` when it is missing — a body sent as
41    /// `application/json` is refused rather than guessed at.
42    UnsupportedMediaType,
43    /// `DataLayer` / `Serialization`. The message is never surfaced.
44    Internal,
45}
46
47impl ErrorCode {
48    /// The HTTP status for this code.
49    pub fn status(self) -> StatusCode {
50        match self {
51            Self::NotFound => StatusCode::NOT_FOUND,
52            Self::Forbidden => StatusCode::FORBIDDEN,
53            Self::PolicyUnavailable => StatusCode::SERVICE_UNAVAILABLE,
54            Self::MissingTenant => StatusCode::BAD_REQUEST,
55            Self::InvalidAttribute => StatusCode::UNPROCESSABLE_ENTITY,
56            Self::InvalidParameter => StatusCode::BAD_REQUEST,
57            Self::Conflict => StatusCode::CONFLICT,
58            Self::PreconditionFailed => StatusCode::PRECONDITION_FAILED,
59            Self::LockContention => StatusCode::SERVICE_UNAVAILABLE,
60            Self::Closing => StatusCode::SERVICE_UNAVAILABLE,
61            Self::Unsupported => StatusCode::NOT_IMPLEMENTED,
62            Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
63            Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
64        }
65    }
66
67    /// The wire value of the JSON:API `code` member.
68    pub fn as_str(self) -> &'static str {
69        match self {
70            Self::NotFound => "not_found",
71            Self::Forbidden => "forbidden",
72            Self::PolicyUnavailable => "policy_unavailable",
73            Self::MissingTenant => "missing_tenant",
74            Self::InvalidAttribute => "invalid_attribute",
75            Self::InvalidParameter => "invalid_parameter",
76            Self::Conflict => "conflict",
77            Self::PreconditionFailed => "precondition_failed",
78            Self::LockContention => "lock_contention",
79            Self::Closing => "closing",
80            Self::Unsupported => "unsupported",
81            Self::UnsupportedMediaType => "unsupported_media_type",
82            Self::Internal => "internal",
83        }
84    }
85
86    /// A short, human-readable title. Safe to show a client.
87    ///
88    /// Not `StatusCode::canonical_reason()`: three of these codes are 503,
89    /// and "Service Unavailable" would collapse the distinction between a
90    /// policy outage, lock contention and a draining server that the codes exist
91    /// to preserve.
92    pub fn title(self) -> &'static str {
93        match self {
94            Self::NotFound => "Not found",
95            Self::Forbidden => "Forbidden",
96            Self::PolicyUnavailable => "Policy unavailable",
97            Self::MissingTenant => "Missing tenant",
98            Self::InvalidAttribute => "Invalid attribute",
99            Self::InvalidParameter => "Invalid query parameter",
100            Self::Conflict => "Conflict",
101            Self::PreconditionFailed => "Precondition failed",
102            Self::LockContention => "Lock contention",
103            Self::Closing => "Server is shutting down",
104            Self::Unsupported => "Unsupported",
105            Self::UnsupportedMediaType => "Unsupported media type",
106            Self::Internal => "Internal server error",
107        }
108    }
109
110    /// Whether the client may retry. Drives `Retry-After`.
111    pub fn is_retriable(self) -> bool {
112        matches!(
113            self,
114            Self::PolicyUnavailable | Self::LockContention | Self::Closing | Self::Conflict
115        )
116    }
117
118    /// Whether the underlying error's message must be withheld from the
119    /// response body.
120    pub fn is_sanitized(self) -> bool {
121        matches!(self, Self::Internal)
122    }
123}
124
125/// The detail text sent in place of a sanitized internal error message.
126pub const INTERNAL_DETAIL: &str = "An internal error occurred.";
127
128/// An error on its way to becoming a JSON:API error object.
129#[derive(Debug, Clone)]
130pub struct JsonApiError {
131    pub code: ErrorCode,
132    detail: Option<String>,
133    source: Option<ErrorSource>,
134    correlation_id: Option<String>,
135    /// Boxed because it is the rare case: a `JsonApiError` is the `Err` of
136    /// most `Result`s in this crate, and a `Translation` inline would widen
137    /// every one of them for a field few errors set.
138    translation: Option<Box<crate::i18n::Translation>>,
139    /// The locale the request asked for, taken from the context so an error
140    /// document can carry `meta.lang` like any other response.
141    ///
142    /// Boxed for the same reason as `translation`: this type is the `Err` of
143    /// most `Result`s in the crate, and most requests send no
144    /// `Accept-Language`.
145    locale: Option<Box<crate::i18n::Locale>>,
146}
147
148impl JsonApiError {
149    /// An error in a request's context.
150    ///
151    /// The usual constructor: every error a handler returns should carry the
152    /// correlation id, so taking the context up front is one call rather than
153    /// a `.in_context(ctx)` remembered at each site.
154    pub fn in_request(code: ErrorCode, ctx: &Context) -> Self {
155        Self::new(code).in_context(ctx)
156    }
157
158    /// A `500` that says nothing.
159    ///
160    /// The detail is dropped by [`ErrorCode::is_sanitized`], so the cause has
161    /// to be logged separately; the correlation id is what connects the two.
162    pub fn internal(ctx: &Context) -> Self {
163        Self::in_request(ErrorCode::Internal, ctx)
164    }
165
166    /// A `422` pointing at one member of the request document.
167    pub fn invalid(ctx: &Context, detail: impl Into<String>, pointer: impl Into<String>) -> Self {
168        Self::in_request(ErrorCode::InvalidAttribute, ctx)
169            .detail(detail)
170            .pointer(pointer)
171    }
172
173    pub fn new(code: ErrorCode) -> Self {
174        Self {
175            code,
176            detail: None,
177            source: None,
178            correlation_id: None,
179            translation: None,
180            locale: None,
181        }
182    }
183
184    /// Attach client-facing detail.
185    ///
186    /// Ignored for codes that must be sanitized — an internal error's message
187    /// can carry a connection string, so this cannot become a leak by
188    /// accident at a call site.
189    pub fn detail(mut self, detail: impl Into<String>) -> Self {
190        if !self.code.is_sanitized() {
191            self.detail = Some(detail.into());
192        }
193        self
194    }
195
196    /// Point at the offending attribute.
197    ///
198    /// A dotted field name becomes a nested JSON pointer:
199    /// `address.city` → `/data/attributes/address/city`.
200    pub fn attribute(mut self, field: &str) -> Self {
201        let pointer = format!("/data/attributes/{}", field.replace('.', "/"));
202        self.source = Some(ErrorSource::pointer(pointer));
203        self
204    }
205
206    /// Point at any member by JSON pointer, e.g.
207    /// `/data/relationships/owner/data`.
208    ///
209    /// [`Self::attribute`] covers the common case; this is for members
210    /// outside `/data/attributes`, which relationships and the document
211    /// envelope both are.
212    #[must_use]
213    pub fn pointer(mut self, pointer: impl Into<String>) -> Self {
214        self.source = Some(ErrorSource::pointer(pointer));
215        self
216    }
217
218    /// Point at the offending query parameter, e.g. `sort`.
219    pub fn parameter(mut self, param: impl Into<String>) -> Self {
220        self.source = Some(ErrorSource::parameter(param));
221        self
222    }
223
224    /// Attach a translation key, so a client can render this failure in its
225    /// own language.
226    ///
227    /// The [`detail`](Self::detail) stays as it is — it is the fallback for a
228    /// client with no catalog — and the key travels beside it under the error
229    /// object's `meta.i18n`. See [`i18n`](crate::i18n) for why the server
230    /// sends a key rather than translated prose.
231    ///
232    /// ```
233    /// use ash_jsonapi::i18n::Translation;
234    /// use ash_jsonapi::{Context, ErrorCode, JsonApiError};
235    ///
236    /// # let ctx = Context::new("");
237    /// let err = JsonApiError::in_request(ErrorCode::InvalidAttribute, &ctx)
238    ///     .detail("must be 80 characters or fewer")
239    ///     .attribute("name")
240    ///     .translate(Translation::new("todo.name.too_long").param("max", 80));
241    ///
242    /// let meta = err.to_object().meta.unwrap();
243    /// assert_eq!(meta["i18n"]["key"], "todo.name.too_long");
244    /// ```
245    ///
246    /// Unlike [`detail`](Self::detail), a key is kept on a sanitized code: it
247    /// names a message this crate chose, not the underlying cause, so it
248    /// cannot leak what `is_sanitized` exists to withhold.
249    #[must_use]
250    pub fn translate(mut self, translation: crate::i18n::Translation) -> Self {
251        self.translation = Some(Box::new(translation));
252        self
253    }
254
255    /// The translation key attached to this error, if any.
256    pub fn translation(&self) -> Option<&crate::i18n::Translation> {
257        self.translation.as_deref()
258    }
259
260    /// Set the correlation id — what makes "here is my error id" resolvable
261    /// in the audit log.
262    pub fn correlation_id(mut self, id: impl Into<String>) -> Self {
263        self.correlation_id = Some(id.into());
264        self
265    }
266
267    /// Take the correlation id from the request's [`Context`].
268    ///
269    /// The normal way to build an error in a handler: the id is already in
270    /// the context, so it never has to be passed separately or remembered.
271    #[must_use]
272    pub fn in_context(mut self, ctx: &Context) -> Self {
273        self.locale = ctx.locale().cloned().map(Box::new);
274        self.correlation_id(ctx.correlation_id())
275    }
276
277    /// The locale this error was built in, if the request named one.
278    pub fn locale(&self) -> Option<&crate::i18n::Locale> {
279        self.locale.as_deref()
280    }
281
282    /// The HTTP status to respond with.
283    pub fn status(&self) -> StatusCode {
284        self.code.status()
285    }
286
287    /// Render the JSON:API error object.
288    pub fn to_object(&self) -> ErrorObject {
289        ErrorObject {
290            id: self.correlation_id.clone(),
291            status: self.code.status().as_u16().to_string(),
292            code: self.code.as_str().to_string(),
293            title: self.code.title().to_string(),
294            detail: if self.code.is_sanitized() {
295                Some(INTERNAL_DETAIL.to_string())
296            } else {
297                self.detail.clone()
298            },
299            source: self.source.clone(),
300            meta: self.meta(),
301        }
302    }
303
304    /// The error object's `meta`, or `None` when there is nothing to put in
305    /// it — an absent member rather than an empty object.
306    fn meta(&self) -> Option<std::collections::BTreeMap<String, serde_json::Value>> {
307        let translation = self.translation.as_deref()?;
308        let encoded = serde_json::to_value(translation).ok()?;
309
310        Some(std::collections::BTreeMap::from([(
311            "i18n".to_string(),
312            encoded,
313        )]))
314    }
315}
316
317impl std::fmt::Display for JsonApiError {
318    /// The title, plus the detail when there is one the client may see.
319    ///
320    /// A sanitized code has no detail to show, so it prints its title alone —
321    /// the same text the client receives, which keeps a log line and a
322    /// response consistent about what was said.
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        match &self.detail {
325            Some(detail) => write!(f, "{}: {detail}", self.code.title()),
326            None => f.write_str(self.code.title()),
327        }
328    }
329}
330
331impl std::error::Error for JsonApiError {}