Skip to main content

jmap_types/
error.rs

1//! RFC 8620 §3.6 JMAP method-level error type ([`JmapError`]).
2
3use crate::Id;
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7/// JMAP method-level error, serializable for inclusion in `methodResponses`.
8///
9/// See RFC 8620 §3.6.2 for the standard error type strings.
10/// The JSON key is `"type"` (not `"error_type"`) per RFC 8620.
11#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
12#[error("{error_type}")]
13#[non_exhaustive]
14pub struct JmapError {
15    /// Error type string per RFC 8620 §3.6.2.
16    #[serde(rename = "type")]
17    pub error_type: String,
18    /// Human-readable description. Omitted from JSON when `None`.
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub description: Option<String>,
21    /// The id of the existing record. Only set for `"alreadyExists"` (RFC 8620 §5.4 MUST).
22    #[serde(rename = "existingId", skip_serializing_if = "Option::is_none")]
23    pub existing_id: Option<Id>,
24    /// Maximum `maxChanges` value the server will accept. Only set for `"tooManyChanges"` (RFC 8620 §9.6.1 MUST).
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub limit: Option<u64>,
27}
28
29impl JmapError {
30    /// RFC 8620 §3.6.2 — "invalidArguments"
31    pub fn invalid_arguments(desc: impl Into<String>) -> Self {
32        Self {
33            error_type: "invalidArguments".into(),
34            description: Some(desc.into()),
35            existing_id: None,
36            limit: None,
37        }
38    }
39
40    /// RFC 8620 §3.6.2 — "forbidden"
41    pub fn forbidden() -> Self {
42        Self {
43            error_type: "forbidden".into(),
44            description: None,
45            existing_id: None,
46            limit: None,
47        }
48    }
49
50    /// RFC 8620 §5.3 — "notFound"
51    pub fn not_found() -> Self {
52        Self {
53            error_type: "notFound".into(),
54            description: None,
55            existing_id: None,
56            limit: None,
57        }
58    }
59
60    /// RFC 8620 §5.1 — "accountNotFound"
61    pub fn account_not_found() -> Self {
62        Self {
63            error_type: "accountNotFound".into(),
64            description: None,
65            existing_id: None,
66            limit: None,
67        }
68    }
69
70    /// RFC 8620 §5.1 — "accountNotSupportedByMethod"
71    pub fn account_not_supported_by_method() -> Self {
72        Self {
73            error_type: "accountNotSupportedByMethod".into(),
74            description: None,
75            existing_id: None,
76            limit: None,
77        }
78    }
79
80    /// RFC 8620 §5.1 — "accountReadOnly"
81    pub fn account_read_only() -> Self {
82        Self {
83            error_type: "accountReadOnly".into(),
84            description: None,
85            existing_id: None,
86            limit: None,
87        }
88    }
89
90    /// RFC 8620 §3.6.2 — "serverUnavailable"
91    pub fn server_unavailable() -> Self {
92        Self {
93            error_type: "serverUnavailable".into(),
94            description: None,
95            existing_id: None,
96            limit: None,
97        }
98    }
99
100    /// RFC 8620 §3.6.2 — "serverFail"
101    pub fn server_fail(desc: impl Into<String>) -> Self {
102        Self {
103            error_type: "serverFail".into(),
104            description: Some(desc.into()),
105            existing_id: None,
106            limit: None,
107        }
108    }
109
110    /// RFC 8620 §3.6.2 — "serverPartialFail"
111    pub fn server_partial_fail() -> Self {
112        Self {
113            error_type: "serverPartialFail".into(),
114            description: None,
115            existing_id: None,
116            limit: None,
117        }
118    }
119
120    /// RFC 8620 §3.6.2 — "unknownMethod"
121    pub fn unknown_method() -> Self {
122        Self {
123            error_type: "unknownMethod".into(),
124            description: None,
125            existing_id: None,
126            limit: None,
127        }
128    }
129
130    /// RFC 8620 §3.6.2 — "invalidResultReference"
131    pub fn invalid_result_reference() -> Self {
132        Self {
133            error_type: "invalidResultReference".into(),
134            description: None,
135            existing_id: None,
136            limit: None,
137        }
138    }
139
140    /// RFC 8620 §5.2 and §5.6 — "cannotCalculateChanges"
141    pub fn cannot_calculate_changes() -> Self {
142        Self {
143            error_type: "cannotCalculateChanges".into(),
144            description: None,
145            existing_id: None,
146            limit: None,
147        }
148    }
149
150    /// RFC 8620 §5.3 — "stateMismatch"
151    pub fn state_mismatch() -> Self {
152        Self {
153            error_type: "stateMismatch".into(),
154            description: None,
155            existing_id: None,
156            limit: None,
157        }
158    }
159
160    /// RFC 8620 §5.3 — "tooLarge"
161    pub fn too_large() -> Self {
162        Self {
163            error_type: "tooLarge".into(),
164            description: None,
165            existing_id: None,
166            limit: None,
167        }
168    }
169
170    /// RFC 8620 §5.1 and §5.3 — "requestTooLarge"
171    pub fn request_too_large() -> Self {
172        Self {
173            error_type: "requestTooLarge".into(),
174            description: None,
175            existing_id: None,
176            limit: None,
177        }
178    }
179
180    /// RFC 8620 §5.3 — "overQuota"
181    pub fn over_quota() -> Self {
182        Self {
183            error_type: "overQuota".into(),
184            description: None,
185            existing_id: None,
186            limit: None,
187        }
188    }
189
190    /// RFC 8620 §5.3 — "rateLimit"
191    pub fn rate_limit() -> Self {
192        Self {
193            error_type: "rateLimit".into(),
194            description: None,
195            existing_id: None,
196            limit: None,
197        }
198    }
199
200    /// RFC 8620 §5.3 — "invalidPatch"
201    pub fn invalid_patch() -> Self {
202        Self {
203            error_type: "invalidPatch".into(),
204            description: None,
205            existing_id: None,
206            limit: None,
207        }
208    }
209
210    /// RFC 8620 §5.3 — "willDestroy"
211    pub fn will_destroy() -> Self {
212        Self {
213            error_type: "willDestroy".into(),
214            description: None,
215            existing_id: None,
216            limit: None,
217        }
218    }
219
220    /// RFC 8620 §5.3 — "invalidProperties"
221    pub fn invalid_properties() -> Self {
222        Self {
223            error_type: "invalidProperties".into(),
224            description: None,
225            existing_id: None,
226            limit: None,
227        }
228    }
229
230    /// RFC 8620 §5.3 — "singleton"
231    pub fn singleton() -> Self {
232        Self {
233            error_type: "singleton".into(),
234            description: None,
235            existing_id: None,
236            limit: None,
237        }
238    }
239
240    /// RFC 8620 §5.5 — "unsupportedFilter"
241    pub fn unsupported_filter() -> Self {
242        Self {
243            error_type: "unsupportedFilter".into(),
244            description: None,
245            existing_id: None,
246            limit: None,
247        }
248    }
249
250    /// RFC 8620 §5.5 — "anchorNotFound"
251    pub fn anchor_not_found() -> Self {
252        Self {
253            error_type: "anchorNotFound".into(),
254            description: None,
255            existing_id: None,
256            limit: None,
257        }
258    }
259
260    /// RFC 8620 §5.4 — "alreadyExists"
261    ///
262    /// `existing_id` is the id of the record that already exists in the target account.
263    /// Per RFC 8620 §5.4, this field MUST be present on the SetError object.
264    pub fn already_exists(existing_id: Id) -> Self {
265        Self {
266            error_type: "alreadyExists".into(),
267            description: None,
268            existing_id: Some(existing_id),
269            limit: None,
270        }
271    }
272
273    /// RFC 8620 §5.4 — "fromAccountNotFound"
274    pub fn from_account_not_found() -> Self {
275        Self {
276            error_type: "fromAccountNotFound".into(),
277            description: None,
278            existing_id: None,
279            limit: None,
280        }
281    }
282
283    /// RFC 8620 §5.4 — "fromAccountNotSupportedByMethod"
284    pub fn from_account_not_supported_by_method() -> Self {
285        Self {
286            error_type: "fromAccountNotSupportedByMethod".into(),
287            description: None,
288            existing_id: None,
289            limit: None,
290        }
291    }
292
293    /// RFC 8620 §5.5 — "unsupportedSort"
294    pub fn unsupported_sort() -> Self {
295        Self {
296            error_type: "unsupportedSort".into(),
297            description: None,
298            existing_id: None,
299            limit: None,
300        }
301    }
302
303    /// RFC 8620 §5.6 — "tooManyChanges"
304    pub fn too_many_changes() -> Self {
305        Self {
306            error_type: "tooManyChanges".into(),
307            description: None,
308            existing_id: None,
309            limit: None,
310        }
311    }
312
313    /// Returns a `tooManyChanges` error with the server's limit included.
314    ///
315    /// Per RFC 8620 §9.6.1, the `limit` field MUST be present so the client
316    /// knows the maximum `maxChanges` value to use on retry.
317    pub fn too_many_changes_with_limit(limit: u64) -> Self {
318        Self {
319            error_type: "tooManyChanges".into(),
320            description: None,
321            existing_id: None,
322            limit: Some(limit),
323        }
324    }
325
326    /// RFC 8620 §3.6.1 — "notJSON" (request-level error)
327    ///
328    /// The request body was not valid JSON or did not have `application/json` content type.
329    pub fn not_json() -> Self {
330        Self {
331            error_type: "notJSON".into(),
332            description: None,
333            existing_id: None,
334            limit: None,
335        }
336    }
337
338    /// RFC 8620 §3.6.1 — "notRequest" (request-level error)
339    ///
340    /// The request parsed as JSON but did not match the JMAP Request object shape.
341    pub fn not_request() -> Self {
342        Self {
343            error_type: "notRequest".into(),
344            description: None,
345            existing_id: None,
346            limit: None,
347        }
348    }
349
350    /// RFC 8620 §3.6.1 — "limit" (request-level error)
351    ///
352    /// The request was rejected because it would exceed a capability limit such as
353    /// `maxCallsInRequest` or `maxSizeRequest`.
354    ///
355    /// `limit_name` is the name of the exceeded limit (e.g. `"maxCallsInRequest"`).
356    /// The HTTP layer MUST forward this name as the `"limit"` property in the
357    /// RFC 7807 Problem Details response body.  The name is stored in
358    /// [`description`][JmapError::description] for that purpose.
359    ///
360    /// **Invariant**: always construct limit errors with this function, never by
361    /// setting `error_type = "limit"` and `description` manually.  The HTTP
362    /// response layer (`jmap-server::RequestError`) reads `description` to
363    /// populate the RFC-required `"limit"` field; a missing description produces
364    /// an invalid response.
365    pub fn limit(limit_name: impl Into<String>) -> Self {
366        Self {
367            error_type: "limit".into(),
368            description: Some(limit_name.into()),
369            existing_id: None,
370            limit: None,
371        }
372    }
373
374    /// RFC 8620 §3.6.1 — "unknownCapability" (request-level error)
375    ///
376    /// The request used a capability URI not recognized by this server.
377    pub fn unknown_capability() -> Self {
378        Self {
379            error_type: "unknownCapability".into(),
380            description: None,
381            existing_id: None,
382            limit: None,
383        }
384    }
385
386    /// Create a `JmapError` with a custom or extension error type string.
387    ///
388    /// Use this when propagating a server error whose `type` value is not one of
389    /// the RFC 8620 standard types, or in tests that need to construct an
390    /// arbitrary `JmapError` value.
391    pub fn custom(error_type: impl Into<String>) -> Self {
392        Self {
393            error_type: error_type.into(),
394            description: None,
395            existing_id: None,
396            limit: None,
397        }
398    }
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    // Independent oracle: RFC 8620 §3.6.2 and §5.x specify these exact type strings.
406
407    #[test]
408    fn invalid_arguments_serializes_type_and_description() {
409        let e = JmapError::invalid_arguments("ids field is required");
410        let json = serde_json::to_string(&e).unwrap();
411        assert!(
412            json.contains("\"type\""),
413            "must use 'type' key per RFC 8620"
414        );
415        assert!(json.contains("\"invalidArguments\""));
416        assert!(json.contains("\"description\""));
417        assert!(json.contains("ids field is required"));
418    }
419
420    #[test]
421    fn forbidden_omits_description() {
422        let e = JmapError::forbidden();
423        let json = serde_json::to_string(&e).unwrap();
424        assert!(json.contains("\"forbidden\""));
425        assert!(
426            !json.contains("\"description\""),
427            "None description must be omitted"
428        );
429    }
430
431    #[test]
432    fn not_found_type_string() {
433        let e = JmapError::not_found();
434        let json = serde_json::to_string(&e).unwrap();
435        assert!(json.contains("\"notFound\""));
436        assert!(!json.contains("\"description\""));
437    }
438
439    #[test]
440    fn account_not_found_type_string() {
441        let e = JmapError::account_not_found();
442        let json = serde_json::to_string(&e).unwrap();
443        assert!(json.contains("\"accountNotFound\""));
444        assert!(!json.contains("\"description\""));
445    }
446
447    #[test]
448    fn account_not_supported_by_method_type_string() {
449        let e = JmapError::account_not_supported_by_method();
450        let json = serde_json::to_string(&e).unwrap();
451        assert!(json.contains("\"accountNotSupportedByMethod\""));
452    }
453
454    #[test]
455    fn account_read_only_type_string() {
456        let e = JmapError::account_read_only();
457        let json = serde_json::to_string(&e).unwrap();
458        assert!(json.contains("\"accountReadOnly\""));
459    }
460
461    #[test]
462    fn server_unavailable_type_string() {
463        let e = JmapError::server_unavailable();
464        let json = serde_json::to_string(&e).unwrap();
465        assert!(json.contains("\"serverUnavailable\""));
466    }
467
468    #[test]
469    fn server_fail_includes_description() {
470        let e = JmapError::server_fail("internal error");
471        let json = serde_json::to_string(&e).unwrap();
472        assert!(json.contains("\"serverFail\""));
473        assert!(json.contains("internal error"));
474    }
475
476    #[test]
477    fn server_partial_fail_type_string() {
478        let e = JmapError::server_partial_fail();
479        let json = serde_json::to_string(&e).unwrap();
480        assert!(json.contains("\"serverPartialFail\""));
481    }
482
483    #[test]
484    fn unknown_method_type_string() {
485        let e = JmapError::unknown_method();
486        let json = serde_json::to_string(&e).unwrap();
487        assert!(json.contains("\"unknownMethod\""));
488    }
489
490    #[test]
491    fn invalid_result_reference_type_string() {
492        let e = JmapError::invalid_result_reference();
493        let json = serde_json::to_string(&e).unwrap();
494        assert!(json.contains("\"invalidResultReference\""));
495    }
496
497    #[test]
498    fn cannot_calculate_changes_type_string() {
499        let e = JmapError::cannot_calculate_changes();
500        let json = serde_json::to_string(&e).unwrap();
501        assert!(json.contains("\"cannotCalculateChanges\""));
502    }
503
504    #[test]
505    fn state_mismatch_type_string() {
506        let e = JmapError::state_mismatch();
507        let json = serde_json::to_string(&e).unwrap();
508        assert!(json.contains("\"stateMismatch\""));
509    }
510
511    #[test]
512    fn too_large_type_string() {
513        let e = JmapError::too_large();
514        let json = serde_json::to_string(&e).unwrap();
515        assert!(json.contains("\"tooLarge\""));
516    }
517
518    #[test]
519    fn request_too_large_type_string() {
520        let e = JmapError::request_too_large();
521        let json = serde_json::to_string(&e).unwrap();
522        assert!(json.contains("\"requestTooLarge\""));
523        assert!(!json.contains("\"description\""));
524    }
525
526    #[test]
527    fn over_quota_type_string() {
528        let e = JmapError::over_quota();
529        let json = serde_json::to_string(&e).unwrap();
530        assert!(json.contains("\"overQuota\""));
531    }
532
533    #[test]
534    fn rate_limit_type_string() {
535        let e = JmapError::rate_limit();
536        let json = serde_json::to_string(&e).unwrap();
537        assert!(json.contains("\"rateLimit\""));
538    }
539
540    #[test]
541    fn invalid_patch_type_string() {
542        let e = JmapError::invalid_patch();
543        let json = serde_json::to_string(&e).unwrap();
544        assert!(json.contains("\"invalidPatch\""));
545    }
546
547    #[test]
548    fn will_destroy_type_string() {
549        let e = JmapError::will_destroy();
550        let json = serde_json::to_string(&e).unwrap();
551        assert!(json.contains("\"willDestroy\""));
552    }
553
554    #[test]
555    fn invalid_properties_type_string() {
556        let e = JmapError::invalid_properties();
557        let json = serde_json::to_string(&e).unwrap();
558        assert!(json.contains("\"invalidProperties\""));
559    }
560
561    #[test]
562    fn singleton_type_string() {
563        let e = JmapError::singleton();
564        let json = serde_json::to_string(&e).unwrap();
565        assert!(json.contains("\"singleton\""));
566    }
567
568    #[test]
569    fn unsupported_filter_type_string() {
570        let e = JmapError::unsupported_filter();
571        let json = serde_json::to_string(&e).unwrap();
572        assert!(json.contains("\"unsupportedFilter\""));
573    }
574
575    #[test]
576    fn anchor_not_found_type_string() {
577        let e = JmapError::anchor_not_found();
578        let json = serde_json::to_string(&e).unwrap();
579        assert!(json.contains("\"anchorNotFound\""));
580    }
581
582    // Oracle: RFC 8620 §5.4 — alreadyExists MUST include existingId of type Id.
583    #[test]
584    fn already_exists_includes_existing_id() {
585        let e = JmapError::already_exists(Id::from("abc123"));
586        let json = serde_json::to_string(&e).unwrap();
587        assert!(json.contains("\"alreadyExists\""));
588        assert!(json.contains("\"existingId\""));
589        assert!(json.contains("\"abc123\""));
590        assert!(!json.contains("\"description\""));
591    }
592
593    #[test]
594    fn from_account_not_found_type_string() {
595        let e = JmapError::from_account_not_found();
596        let json = serde_json::to_string(&e).unwrap();
597        assert!(json.contains("\"fromAccountNotFound\""));
598        assert!(!json.contains("\"description\""));
599    }
600
601    #[test]
602    fn from_account_not_supported_by_method_type_string() {
603        let e = JmapError::from_account_not_supported_by_method();
604        let json = serde_json::to_string(&e).unwrap();
605        assert!(json.contains("\"fromAccountNotSupportedByMethod\""));
606        assert!(!json.contains("\"description\""));
607    }
608
609    #[test]
610    fn unsupported_sort_type_string() {
611        let e = JmapError::unsupported_sort();
612        let json = serde_json::to_string(&e).unwrap();
613        assert!(json.contains("\"unsupportedSort\""));
614        assert!(!json.contains("\"description\""));
615    }
616
617    #[test]
618    fn too_many_changes_type_string() {
619        let e = JmapError::too_many_changes();
620        let json = serde_json::to_string(&e).unwrap();
621        assert!(json.contains("\"tooManyChanges\""));
622        assert!(!json.contains("\"description\""));
623    }
624
625    #[test]
626    fn too_many_changes_with_limit_serializes_limit_field() {
627        let err = JmapError::too_many_changes_with_limit(100);
628        let v = serde_json::to_value(&err).unwrap();
629        assert_eq!(v["type"], "tooManyChanges");
630        assert_eq!(v["limit"], 100u64);
631        assert!(v.get("description").is_none());
632    }
633
634    #[test]
635    fn too_many_changes_without_limit_has_no_limit_field() {
636        let err = JmapError::too_many_changes();
637        let v = serde_json::to_value(&err).unwrap();
638        assert_eq!(v["type"], "tooManyChanges");
639        assert!(v.get("limit").is_none());
640    }
641
642    #[test]
643    fn not_json_type_string() {
644        let e = JmapError::not_json();
645        let json = serde_json::to_string(&e).unwrap();
646        assert!(json.contains("\"notJSON\""));
647        assert!(!json.contains("\"description\""));
648    }
649
650    #[test]
651    fn not_request_type_string() {
652        let e = JmapError::not_request();
653        let json = serde_json::to_string(&e).unwrap();
654        assert!(json.contains("\"notRequest\""));
655        assert!(!json.contains("\"description\""));
656    }
657
658    #[test]
659    fn limit_includes_limit_name_in_description() {
660        // Oracle: the limit name is stored in description so the HTTP layer
661        // can forward it as the "limit" field in RFC 7807 Problem Details.
662        let e = JmapError::limit("maxCallsInRequest");
663        let json = serde_json::to_string(&e).unwrap();
664        assert!(json.contains("\"limit\""));
665        assert!(json.contains("\"maxCallsInRequest\""));
666    }
667
668    #[test]
669    fn unknown_capability_type_string() {
670        let e = JmapError::unknown_capability();
671        let json = serde_json::to_string(&e).unwrap();
672        assert!(json.contains("\"unknownCapability\""));
673        assert!(!json.contains("\"description\""));
674    }
675
676    #[test]
677    fn custom_error_type_round_trips() {
678        let e = JmapError::custom("urn:example:customError");
679        assert_eq!(e.error_type, "urn:example:customError");
680        let json = serde_json::to_string(&e).unwrap();
681        assert!(json.contains("\"urn:example:customError\""));
682        let restored: JmapError = serde_json::from_str(&json).unwrap();
683        assert_eq!(restored.error_type, "urn:example:customError");
684    }
685
686    #[test]
687    fn round_trip_deserialize() {
688        // Verify the "type" rename survives a JSON round-trip.
689        let original = JmapError::invalid_arguments("test");
690        let json = serde_json::to_string(&original).unwrap();
691        let restored: JmapError = serde_json::from_str(&json).unwrap();
692        assert_eq!(restored.error_type, "invalidArguments");
693        assert_eq!(restored.description.as_deref(), Some("test"));
694    }
695
696    // Oracle: RFC 8620 §3.4.1 fixture — methodResponses[3] is ["error", {"type":"unknownMethod"}, "c3"]
697    #[test]
698    fn fixture_response_contains_unknown_method_error() {
699        let raw = include_str!("../tests/fixtures/rfc8620-response.json");
700        let v: serde_json::Value = serde_json::from_str(raw).expect("parse fixture");
701        let inv = &v["methodResponses"][3];
702        assert_eq!(inv[0], "error");
703        assert_eq!(inv[1]["type"], "unknownMethod");
704        assert_eq!(inv[2], "c3");
705    }
706}