1use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7#[non_exhaustive]
19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub enum MethodErrorType {
21 UnknownCapability,
23 NotJson,
26 NotRequest,
29 Limit,
32 ServerUnavailable,
35 ServerFail,
37 ServerPartialFail,
39 UnknownMethod,
41 InvalidArguments,
43 InvalidResultReference,
45 Forbidden,
47 AccountNotFound,
50 AccountNotSupportedByMethod,
52 AccountReadOnly,
54 RequestTooLarge,
56 CannotCalculateChanges,
59 StateMismatch,
62 FromAccountNotFound,
65 FromAccountNotSupportedByMethod,
68 AnchorNotFound,
70 UnsupportedSort,
72 UnsupportedFilter,
74 TooManyChanges,
76 Other(String),
78}
79
80crate::impl_string_enum!(
81 MethodErrorType,
82 "a JMAP method error type string",
83 "unknownCapability" => UnknownCapability,
84 "notJSON" => NotJson,
85 "notRequest" => NotRequest,
86 "limit" => Limit,
87 "serverUnavailable" => ServerUnavailable,
88 "serverFail" => ServerFail,
89 "serverPartialFail" => ServerPartialFail,
90 "unknownMethod" => UnknownMethod,
91 "invalidArguments" => InvalidArguments,
92 "invalidResultReference" => InvalidResultReference,
93 "forbidden" => Forbidden,
94 "accountNotFound" => AccountNotFound,
95 "accountNotSupportedByMethod" => AccountNotSupportedByMethod,
96 "accountReadOnly" => AccountReadOnly,
97 "requestTooLarge" => RequestTooLarge,
98 "cannotCalculateChanges" => CannotCalculateChanges,
99 "stateMismatch" => StateMismatch,
100 "fromAccountNotFound" => FromAccountNotFound,
101 "fromAccountNotSupportedByMethod" => FromAccountNotSupportedByMethod,
102 "anchorNotFound" => AnchorNotFound,
103 "unsupportedSort" => UnsupportedSort,
104 "unsupportedFilter" => UnsupportedFilter,
105 "tooManyChanges" => TooManyChanges,
106);
107
108#[non_exhaustive]
113#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
114#[error("{error_type}")]
115pub struct JmapError {
116 #[serde(rename = "type")]
118 pub error_type: MethodErrorType,
119 #[serde(skip_serializing_if = "Option::is_none")]
121 pub description: Option<String>,
122 #[serde(skip_serializing_if = "Option::is_none")]
124 pub limit: Option<u64>,
125 #[serde(skip)]
134 pub limit_name: Option<String>,
135 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
140 pub extra: serde_json::Map<String, serde_json::Value>,
141}
142
143impl JmapError {
144 pub fn invalid_arguments(desc: impl Into<String>) -> Self {
146 Self {
147 error_type: MethodErrorType::InvalidArguments,
148 description: Some(desc.into()),
149 limit: None,
150 limit_name: None,
151 extra: serde_json::Map::new(),
152 }
153 }
154
155 pub fn forbidden() -> Self {
157 Self {
158 error_type: MethodErrorType::Forbidden,
159 description: None,
160 limit: None,
161 limit_name: None,
162 extra: serde_json::Map::new(),
163 }
164 }
165
166 pub fn account_not_found() -> Self {
168 Self {
169 error_type: MethodErrorType::AccountNotFound,
170 description: None,
171 limit: None,
172 limit_name: None,
173 extra: serde_json::Map::new(),
174 }
175 }
176
177 pub fn account_not_supported_by_method() -> Self {
179 Self {
180 error_type: MethodErrorType::AccountNotSupportedByMethod,
181 description: None,
182 limit: None,
183 limit_name: None,
184 extra: serde_json::Map::new(),
185 }
186 }
187
188 pub fn account_read_only() -> Self {
190 Self {
191 error_type: MethodErrorType::AccountReadOnly,
192 description: None,
193 limit: None,
194 limit_name: None,
195 extra: serde_json::Map::new(),
196 }
197 }
198
199 pub fn server_unavailable() -> Self {
201 Self {
202 error_type: MethodErrorType::ServerUnavailable,
203 description: None,
204 limit: None,
205 limit_name: None,
206 extra: serde_json::Map::new(),
207 }
208 }
209
210 pub fn server_fail(desc: impl Into<String>) -> Self {
212 Self {
213 error_type: MethodErrorType::ServerFail,
214 description: Some(desc.into()),
215 limit: None,
216 limit_name: None,
217 extra: serde_json::Map::new(),
218 }
219 }
220
221 pub fn server_partial_fail() -> Self {
223 Self {
224 error_type: MethodErrorType::ServerPartialFail,
225 description: None,
226 limit: None,
227 limit_name: None,
228 extra: serde_json::Map::new(),
229 }
230 }
231
232 pub fn unknown_method() -> Self {
234 Self {
235 error_type: MethodErrorType::UnknownMethod,
236 description: None,
237 limit: None,
238 limit_name: None,
239 extra: serde_json::Map::new(),
240 }
241 }
242
243 pub fn invalid_result_reference() -> Self {
245 Self {
246 error_type: MethodErrorType::InvalidResultReference,
247 description: None,
248 limit: None,
249 limit_name: None,
250 extra: serde_json::Map::new(),
251 }
252 }
253
254 pub fn cannot_calculate_changes() -> Self {
256 Self {
257 error_type: MethodErrorType::CannotCalculateChanges,
258 description: None,
259 limit: None,
260 limit_name: None,
261 extra: serde_json::Map::new(),
262 }
263 }
264
265 pub fn state_mismatch() -> Self {
267 Self {
268 error_type: MethodErrorType::StateMismatch,
269 description: None,
270 limit: None,
271 limit_name: None,
272 extra: serde_json::Map::new(),
273 }
274 }
275
276 pub fn too_large() -> Self {
280 Self {
281 error_type: MethodErrorType::from("tooLarge"),
282 description: None,
283 limit: None,
284 limit_name: None,
285 extra: serde_json::Map::new(),
286 }
287 }
288
289 pub fn request_too_large() -> Self {
291 Self {
292 error_type: MethodErrorType::RequestTooLarge,
293 description: None,
294 limit: None,
295 limit_name: None,
296 extra: serde_json::Map::new(),
297 }
298 }
299
300 pub fn rate_limit() -> Self {
304 Self {
305 error_type: MethodErrorType::from("rateLimit"),
306 description: None,
307 limit: None,
308 limit_name: None,
309 extra: serde_json::Map::new(),
310 }
311 }
312
313 pub fn unsupported_filter() -> Self {
315 Self {
316 error_type: MethodErrorType::UnsupportedFilter,
317 description: None,
318 limit: None,
319 limit_name: None,
320 extra: serde_json::Map::new(),
321 }
322 }
323
324 pub fn anchor_not_found() -> Self {
326 Self {
327 error_type: MethodErrorType::AnchorNotFound,
328 description: None,
329 limit: None,
330 limit_name: None,
331 extra: serde_json::Map::new(),
332 }
333 }
334
335 pub fn from_account_not_found() -> Self {
337 Self {
338 error_type: MethodErrorType::FromAccountNotFound,
339 description: None,
340 limit: None,
341 limit_name: None,
342 extra: serde_json::Map::new(),
343 }
344 }
345
346 pub fn from_account_not_supported_by_method() -> Self {
348 Self {
349 error_type: MethodErrorType::FromAccountNotSupportedByMethod,
350 description: None,
351 limit: None,
352 limit_name: None,
353 extra: serde_json::Map::new(),
354 }
355 }
356
357 pub fn unsupported_sort() -> Self {
359 Self {
360 error_type: MethodErrorType::UnsupportedSort,
361 description: None,
362 limit: None,
363 limit_name: None,
364 extra: serde_json::Map::new(),
365 }
366 }
367
368 pub fn too_many_changes_with_limit(limit: u64) -> Self {
373 Self {
374 error_type: MethodErrorType::TooManyChanges,
375 description: None,
376 limit: Some(limit),
377 limit_name: None,
378 extra: serde_json::Map::new(),
379 }
380 }
381
382 pub fn not_json() -> Self {
386 Self {
387 error_type: MethodErrorType::NotJson,
388 description: None,
389 limit: None,
390 limit_name: None,
391 extra: serde_json::Map::new(),
392 }
393 }
394
395 pub fn not_request() -> Self {
399 Self {
400 error_type: MethodErrorType::NotRequest,
401 description: None,
402 limit: None,
403 limit_name: None,
404 extra: serde_json::Map::new(),
405 }
406 }
407
408 pub fn limit(limit_name: impl Into<String>) -> Self {
418 Self {
419 error_type: MethodErrorType::Limit,
420 description: None,
421 limit: None,
422 limit_name: Some(limit_name.into()),
423 extra: serde_json::Map::new(),
424 }
425 }
426
427 pub fn unknown_capability_with_detail(uri: impl Into<String>) -> Self {
439 Self {
440 error_type: MethodErrorType::UnknownCapability,
441 description: Some(uri.into()),
442 limit: None,
443 limit_name: None,
444 extra: serde_json::Map::new(),
445 }
446 }
447
448 pub fn custom(error_type: impl Into<MethodErrorType>) -> Self {
454 Self {
455 error_type: error_type.into(),
456 description: None,
457 limit: None,
458 limit_name: None,
459 extra: serde_json::Map::new(),
460 }
461 }
462}
463
464#[must_use]
474pub fn json_type_name(v: &serde_json::Value) -> &'static str {
475 match v {
476 serde_json::Value::Null => "null",
477 serde_json::Value::Bool(_) => "boolean",
478 serde_json::Value::Number(_) => "number",
479 serde_json::Value::String(_) => "string",
480 serde_json::Value::Array(_) => "array",
481 serde_json::Value::Object(_) => "object",
482 }
483}
484
485#[cfg(test)]
486mod tests {
487 use super::*;
488
489 #[test]
492 fn invalid_arguments_serializes_type_and_description() {
493 let e = JmapError::invalid_arguments("ids field is required");
494 let json = serde_json::to_string(&e).unwrap();
495 assert!(
496 json.contains("\"type\""),
497 "must use 'type' key per RFC 8620"
498 );
499 assert!(json.contains("\"invalidArguments\""));
500 assert!(json.contains("\"description\""));
501 assert!(json.contains("ids field is required"));
502 }
503
504 #[test]
505 fn forbidden_omits_description() {
506 let e = JmapError::forbidden();
507 let json = serde_json::to_string(&e).unwrap();
508 assert!(json.contains("\"forbidden\""));
509 assert!(
510 !json.contains("\"description\""),
511 "None description must be omitted"
512 );
513 }
514
515 #[test]
516 fn account_not_found_type_string() {
517 let e = JmapError::account_not_found();
518 let json = serde_json::to_string(&e).unwrap();
519 assert!(json.contains("\"accountNotFound\""));
520 assert!(!json.contains("\"description\""));
521 }
522
523 #[test]
524 fn account_not_supported_by_method_type_string() {
525 let e = JmapError::account_not_supported_by_method();
526 let json = serde_json::to_string(&e).unwrap();
527 assert!(json.contains("\"accountNotSupportedByMethod\""));
528 }
529
530 #[test]
531 fn account_read_only_type_string() {
532 let e = JmapError::account_read_only();
533 let json = serde_json::to_string(&e).unwrap();
534 assert!(json.contains("\"accountReadOnly\""));
535 }
536
537 #[test]
538 fn server_unavailable_type_string() {
539 let e = JmapError::server_unavailable();
540 let json = serde_json::to_string(&e).unwrap();
541 assert!(json.contains("\"serverUnavailable\""));
542 }
543
544 #[test]
545 fn server_fail_includes_description() {
546 let e = JmapError::server_fail("internal error");
547 let json = serde_json::to_string(&e).unwrap();
548 assert!(json.contains("\"serverFail\""));
549 assert!(json.contains("internal error"));
550 }
551
552 #[test]
553 fn server_partial_fail_type_string() {
554 let e = JmapError::server_partial_fail();
555 let json = serde_json::to_string(&e).unwrap();
556 assert!(json.contains("\"serverPartialFail\""));
557 }
558
559 #[test]
560 fn unknown_method_type_string() {
561 let e = JmapError::unknown_method();
562 let json = serde_json::to_string(&e).unwrap();
563 assert!(json.contains("\"unknownMethod\""));
564 }
565
566 #[test]
567 fn invalid_result_reference_type_string() {
568 let e = JmapError::invalid_result_reference();
569 let json = serde_json::to_string(&e).unwrap();
570 assert!(json.contains("\"invalidResultReference\""));
571 }
572
573 #[test]
574 fn cannot_calculate_changes_type_string() {
575 let e = JmapError::cannot_calculate_changes();
576 let json = serde_json::to_string(&e).unwrap();
577 assert!(json.contains("\"cannotCalculateChanges\""));
578 }
579
580 #[test]
581 fn state_mismatch_type_string() {
582 let e = JmapError::state_mismatch();
583 let json = serde_json::to_string(&e).unwrap();
584 assert!(json.contains("\"stateMismatch\""));
585 }
586
587 #[test]
588 fn too_large_type_string() {
589 let e = JmapError::too_large();
590 let json = serde_json::to_string(&e).unwrap();
591 assert!(json.contains("\"tooLarge\""));
592 }
593
594 #[test]
595 fn request_too_large_type_string() {
596 let e = JmapError::request_too_large();
597 let json = serde_json::to_string(&e).unwrap();
598 assert!(json.contains("\"requestTooLarge\""));
599 assert!(!json.contains("\"description\""));
600 }
601
602 #[test]
603 fn rate_limit_type_string() {
604 let e = JmapError::rate_limit();
605 let json = serde_json::to_string(&e).unwrap();
606 assert!(json.contains("\"rateLimit\""));
607 }
608
609 #[test]
610 fn unsupported_filter_type_string() {
611 let e = JmapError::unsupported_filter();
612 let json = serde_json::to_string(&e).unwrap();
613 assert!(json.contains("\"unsupportedFilter\""));
614 }
615
616 #[test]
617 fn anchor_not_found_type_string() {
618 let e = JmapError::anchor_not_found();
619 let json = serde_json::to_string(&e).unwrap();
620 assert!(json.contains("\"anchorNotFound\""));
621 }
622
623 #[test]
624 fn from_account_not_found_type_string() {
625 let e = JmapError::from_account_not_found();
626 let json = serde_json::to_string(&e).unwrap();
627 assert!(json.contains("\"fromAccountNotFound\""));
628 assert!(!json.contains("\"description\""));
629 }
630
631 #[test]
632 fn from_account_not_supported_by_method_type_string() {
633 let e = JmapError::from_account_not_supported_by_method();
634 let json = serde_json::to_string(&e).unwrap();
635 assert!(json.contains("\"fromAccountNotSupportedByMethod\""));
636 assert!(!json.contains("\"description\""));
637 }
638
639 #[test]
640 fn unsupported_sort_type_string() {
641 let e = JmapError::unsupported_sort();
642 let json = serde_json::to_string(&e).unwrap();
643 assert!(json.contains("\"unsupportedSort\""));
644 assert!(!json.contains("\"description\""));
645 }
646
647 #[test]
648 fn too_many_changes_with_limit_serializes_limit_field() {
649 let err = JmapError::too_many_changes_with_limit(100);
650 let v = serde_json::to_value(&err).unwrap();
651 assert_eq!(v["type"], "tooManyChanges");
652 assert_eq!(v["limit"], 100u64);
653 assert!(v.get("description").is_none());
654 }
655
656 #[test]
657 fn not_json_type_string() {
658 let e = JmapError::not_json();
659 let json = serde_json::to_string(&e).unwrap();
660 assert!(json.contains("\"notJSON\""));
661 assert!(!json.contains("\"description\""));
662 }
663
664 #[test]
665 fn not_request_type_string() {
666 let e = JmapError::not_request();
667 let json = serde_json::to_string(&e).unwrap();
668 assert!(json.contains("\"notRequest\""));
669 assert!(!json.contains("\"description\""));
670 }
671
672 #[test]
673 fn limit_carries_limit_name_in_its_own_field() {
674 let e = JmapError::limit("maxCallsInRequest");
678 assert_eq!(e.error_type, MethodErrorType::Limit);
679 assert_eq!(e.limit_name.as_deref(), Some("maxCallsInRequest"));
680 assert_eq!(e.description, None);
681 assert_eq!(
684 serde_json::to_value(&e).unwrap(),
685 serde_json::json!({"type": "limit"})
686 );
687 }
688
689 #[test]
691 fn unknown_capability_with_detail_includes_uri() {
692 let e = JmapError::unknown_capability_with_detail("urn:example:unknown");
693 assert_eq!(e.error_type, MethodErrorType::UnknownCapability);
694 assert_eq!(e.description.as_deref(), Some("urn:example:unknown"));
695 }
696
697 #[test]
698 fn custom_error_type_round_trips() {
699 let e = JmapError::custom("urn:example:customError");
700 assert_eq!(
701 e.error_type,
702 MethodErrorType::Other("urn:example:customError".to_owned())
703 );
704 let json = serde_json::to_string(&e).unwrap();
705 assert!(json.contains("\"urn:example:customError\""));
706 let restored: JmapError = serde_json::from_str(&json).unwrap();
707 assert_eq!(restored, e);
708 }
709
710 #[test]
711 fn round_trip_deserialize() {
712 let original = JmapError::invalid_arguments("test");
714 let json = serde_json::to_string(&original).unwrap();
715 let restored: JmapError = serde_json::from_str(&json).unwrap();
716 assert_eq!(restored.error_type, MethodErrorType::InvalidArguments);
717 assert_eq!(restored.description.as_deref(), Some("test"));
718 }
719
720 #[test]
724 fn method_error_type_all_known_variants_round_trip() {
725 let cases: &[(MethodErrorType, &str)] = &[
726 (MethodErrorType::UnknownCapability, "unknownCapability"),
727 (MethodErrorType::NotJson, "notJSON"),
728 (MethodErrorType::NotRequest, "notRequest"),
729 (MethodErrorType::Limit, "limit"),
730 (MethodErrorType::ServerUnavailable, "serverUnavailable"),
731 (MethodErrorType::ServerFail, "serverFail"),
732 (MethodErrorType::ServerPartialFail, "serverPartialFail"),
733 (MethodErrorType::UnknownMethod, "unknownMethod"),
734 (MethodErrorType::InvalidArguments, "invalidArguments"),
735 (
736 MethodErrorType::InvalidResultReference,
737 "invalidResultReference",
738 ),
739 (MethodErrorType::Forbidden, "forbidden"),
740 (MethodErrorType::AccountNotFound, "accountNotFound"),
741 (
742 MethodErrorType::AccountNotSupportedByMethod,
743 "accountNotSupportedByMethod",
744 ),
745 (MethodErrorType::AccountReadOnly, "accountReadOnly"),
746 (MethodErrorType::RequestTooLarge, "requestTooLarge"),
747 (
748 MethodErrorType::CannotCalculateChanges,
749 "cannotCalculateChanges",
750 ),
751 (MethodErrorType::StateMismatch, "stateMismatch"),
752 (MethodErrorType::FromAccountNotFound, "fromAccountNotFound"),
753 (
754 MethodErrorType::FromAccountNotSupportedByMethod,
755 "fromAccountNotSupportedByMethod",
756 ),
757 (MethodErrorType::AnchorNotFound, "anchorNotFound"),
758 (MethodErrorType::UnsupportedSort, "unsupportedSort"),
759 (MethodErrorType::UnsupportedFilter, "unsupportedFilter"),
760 (MethodErrorType::TooManyChanges, "tooManyChanges"),
761 ];
762 for (variant, wire) in cases {
763 assert_eq!(
764 serde_json::to_value(variant).unwrap(),
765 serde_json::Value::String((*wire).to_owned())
766 );
767 let decoded: MethodErrorType =
768 serde_json::from_value(serde_json::Value::String((*wire).to_owned())).unwrap();
769 assert_eq!(&decoded, variant, "{wire} must decode to its variant");
770 assert_eq!(&MethodErrorType::from(*wire), variant);
771 }
772 let decoded: MethodErrorType = serde_json::from_str(r#""rateLimited""#).unwrap();
774 assert_eq!(decoded, MethodErrorType::Other("rateLimited".to_owned()));
775 assert_eq!(serde_json::to_string(&decoded).unwrap(), r#""rateLimited""#);
776 }
777
778 #[test]
780 fn fixture_response_contains_unknown_method_error() {
781 let raw = include_str!("../tests/fixtures/rfc8620-response.json");
782 let v: serde_json::Value = serde_json::from_str(raw).expect("parse fixture");
783 let inv = &v["methodResponses"][3];
784 assert_eq!(inv[0], "error");
785 assert_eq!(inv[1]["type"], "unknownMethod");
786 assert_eq!(inv[2], "c3");
787 }
788
789 #[test]
792 fn unknown_properties_round_trip() {
793 let wire = serde_json::json!({
794 "type": "urn:example:custom",
795 "description": "d",
796 "detail": {"n": 1},
797 "ids": ["a"]
798 });
799 let e: JmapError = serde_json::from_value(wire.clone()).unwrap();
800 assert_eq!(e.description.as_deref(), Some("d"));
801 assert_eq!(e.extra.len(), 2);
802 assert_eq!(e.extra["detail"], serde_json::json!({"n": 1}));
803 assert_eq!(serde_json::to_value(&e).unwrap(), wire);
804 assert_eq!(
806 serde_json::to_value(JmapError::state_mismatch()).unwrap(),
807 serde_json::json!({"type": "stateMismatch"})
808 );
809 }
810
811 #[test]
815 fn size_stays_small() {
816 let size = std::mem::size_of::<JmapError>();
819 let map = std::mem::size_of::<serde_json::Map<String, serde_json::Value>>();
820 assert!(size <= 88 + map, "JmapError is {size} bytes");
821 }
822}