Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The error object Microsoft Graph returns instead of a result.//!//! ```json//! {"error":{"code":"TooManyRequests","message":"Please retry again later.",//! "innerError":{"code":"429","date":"2020-08-18T12:51:51",//! "request-id":"94fb3b52-452a-4535-a601-69e0a90e3aa2",//! "status":"429"}}}//! ```//!//! Three things about it decide how it is read here, and all three differ from//! the Google error object that the sibling Gmail library parses.//!//! **`code` is a string, not a number.** `badRequest`, `ErrorItemNotFound`,//! `InvalidAuthenticationToken`. Microsoft's own guidance is to branch on this//! and never on `message`, which is not localised and not stable.//!//! **The casing of that string is not consistent.** Graph ships//! `TooManyRequests`, `badRequest` and `activityLimitReached` side by side, so//! every comparison here is case-insensitive. Matching exactly is the bug that//! makes throttling handling work in a test and not in production.//!//! **`innerError` nests, and the useful code is usually at the bottom.** The//! reference says to walk the chain and use the most specific code understood;//! `mostSpecificCode` is that walk, and `hasCode` searches the whole chain//! rather than just the top.//!//! Everything is optional, because a failure is exactly the situation in which//! a server is least likely to send what it promised: a proxy in front of Graph//! answers 502 with HTML, and a revoked token has come back with an empty body.//! `parse` reports that as `error.NotAnError` rather than inventing fields.
const ApiError = @This();
const std = @import("std");
const json = @import("json.zig");
/// The machine-readable code, and the only member worth branching on.code: ?[]const u8,/// A sentence meant for a developer. Not localised, not stable, and not to be/// shown to a user or matched against.message: ?[]const u8,/// The `innerError` chain, outermost first. Usually one deep, occasionally/// three.inner: []const Inner,/// `details`, which a batch or bulk request uses to report one failure per/// operation.details: []const Detail,/// The identifier to quote in a support request. Read from wherever in the/// chain it appears, since Graph puts it on the inner error rather than the/// outer one.request_id: ?[]const u8,client_request_id: ?[]const u8,/// When the service says the failure happened, which is worth having when it/// disagrees with this machine's clock.date: ?[]const u8,
arena: std.heap.ArenaAllocator,
pub const Inner = struct { code: ?[]const u8 = null, message: ?[]const u8 = null,};
pub const Detail = struct { code: ?[]const u8 = null, message: ?[]const u8 = null, /// Which property was at fault, for a validation failure. target: ?[]const u8 = null,};
/// How far down an `innerError` chain this will follow.////// The chain is recursive and arrives from the network, so it needs a bound./// Three is the deepest Graph has been observed to send; the cap is well above/// that and anything past it is dropped rather than being an error.pub const max_inner_depth = 16;
pub const ParseError = error{ /// The body was not JSON, or was JSON with no `error` object in it. A /// non-2xx response that parses to this was not a Graph error but /// something in front of Graph. NotAnError,} || std.mem.Allocator.Error;
pub fn parse(gpa: std.mem.Allocator, body: []const u8) ParseError!ApiError { var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const alloc = arena.allocator();
const root = std.json.parseFromSliceLeaky(std.json.Value, alloc, body, .{}) catch return error.NotAnError; if (root != .object) return error.NotAnError;
const err = root.object.get("error") orelse return error.NotAnError; // The *OAuth* endpoints at login.microsoftonline.com put a bare string // here -- `"error": "invalid_grant"` -- which is the RFC 6749 shape that // `oidc.ErrorResponse` reads and not this one. if (err != .object) return error.NotAnError;
var inner: std.ArrayList(Inner) = .empty; var request_id = json.string(err, "request-id"); var client_request_id = json.string(err, "client-request-id"); var date = json.string(err, "date");
// Both spellings, because Graph's own documentation uses both: the error // resource type says `innererror` and every example response says // `innerError`. var node: ?std.json.Value = json.object(err, "innerError") orelse json.object(err, "innererror"); var depth: usize = 0; while (node) |n| : (depth += 1) { if (depth >= max_inner_depth) break; try inner.append(alloc, .{ .code = json.string(n, "code"), .message = json.string(n, "message"), }); // The identifiers live on whichever level carries them, so the first // one found wins and the walk keeps going for the codes. if (request_id == null) request_id = json.string(n, "request-id"); if (client_request_id == null) client_request_id = json.string(n, "client-request-id"); if (date == null) date = json.string(n, "date");
node = json.object(n, "innerError") orelse json.object(n, "innererror"); }
var details: std.ArrayList(Detail) = .empty; if (json.array(err, "details")) |items| { try details.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { if (item != .object) continue; details.appendAssumeCapacity(.{ .code = json.string(item, "code"), .message = json.string(item, "message"), .target = json.string(item, "target"), }); } }
return .{ .code = json.string(err, "code"), .message = json.string(err, "message"), .inner = try inner.toOwnedSlice(alloc), .details = try details.toOwnedSlice(alloc), .request_id = request_id, .client_request_id = client_request_id, .date = date, .arena = arena, };}
pub fn deinit(e: *ApiError) void { e.arena.deinit(); e.* = undefined;}
/// The deepest `innerError` code there is, falling back to the outer one.////// This is what the reference means by "loop through all the nested error/// codes that are available and use the most detailed one that they/// understand" -- with the caveat that the innermost code is sometimes just/// the status repeated as a string, which is why `hasCode` searches the whole/// chain rather than only this.pub fn mostSpecificCode(e: *const ApiError) ?[]const u8 { var i = e.inner.len; while (i > 0) { i -= 1; if (e.inner[i].code) |c| if (c.len > 0) return c; } return e.code;}
/// Whether `name` appears anywhere in the chain, compared case-insensitively.////// Case-insensitively because Graph is not consistent about it: the same/// service ships `TooManyRequests`, `badRequest` and `activityLimitReached`.pub fn hasCode(e: *const ApiError, name: []const u8) bool { if (e.code) |c| if (std.ascii.eqlIgnoreCase(c, name)) return true; for (e.inner) |i| { if (i.code) |c| if (std.ascii.eqlIgnoreCase(c, name)) return true; } for (e.details) |d| { if (d.code) |c| if (std.ascii.eqlIgnoreCase(c, name)) return true; } return false;}
/// Whether this failure is one the same request might survive if it were sent/// again after a pause.////// Throttling is the reason a Graph client needs this at all: a mailbox walk/// runs into 429 as a matter of routine and it means "slow down", not "stop"./// Note what is *not* here -- 403. Graph uses it for permission and licensing/// rather than for quota, unlike Google, so retrying one only spends the/// budget on a certainty.pub fn isRetryable(e: *const ApiError, status: std.http.Status) bool { // A refused token and a denied permission are never things to wait out, // whatever the body says. This comes first because the code fallback at // the bottom would otherwise claim a 401 whose body happens to carry // `TooManyRequests` -- a combination that is contradictory but that a // gateway in front of Graph really can produce, and that `tests/fuzz.zig` // found by building one. Retrying it would spend the retry budget instead // of refreshing the token, which is the one thing that would have worked. if (status == .unauthorized or status == .forbidden) return false;
if (status == .too_many_requests) return true; // 509, which is not in `std.http.Status`, is the bandwidth cap and is // explicitly described as retryable after more time. if (@intFromEnum(status) == 509) return true; if (status.class() == .server_error) return true;
// A concurrency violation on a directory write: the reference says to // repeat it after a delay with exponential backoff. if (status == .conflict) return e.hasCode("Directory_ConcurrencyViolation");
// And the code, for a service that sends one of these with a status this // has not already accepted. return e.hasCode("TooManyRequests") or e.hasCode("activityLimitReached") or e.hasCode("serviceNotAvailable") or e.hasCode("unknownError");}
/// Whether the access token is the problem, so that a caller holding a refresh/// token knows to spend it rather than to give up.////// `InvalidAuthenticationToken` is the one Graph actually sends for an expired/// token; the inner code is usually the more descriptive `CompactToken parsing/// failed` or `Lifetime validation failed`.pub fn isAuthFailure(e: *const ApiError, status: std.http.Status) bool { if (status == .unauthorized) return true; return e.hasCode("InvalidAuthenticationToken") or e.hasCode("unauthenticated") or e.hasCode("tokenExpired");}
/// Whether the token is good but is not allowed to do this -- the scope is too/// narrow, the mailbox is somebody else's, or the tenant has no licence for it.////// Split from `isAuthFailure` because the answers differ: this one is not/// fixed by refreshing, only by asking for different scopes or by an/// administrator granting consent.pub fn isPermissionFailure(e: *const ApiError, status: std.http.Status) bool { if (status == .forbidden) return true; return e.hasCode("accessDenied") or e.hasCode("ErrorAccessDenied") or e.hasCode("authorizationRequestDenied");}
/// Whether the thing asked for is not there: a message that has been deleted/// out from under a walk, or a folder id from a previous run.pub fn isNotFound(e: *const ApiError, status: std.http.Status) bool { if (status == .not_found) return true; return e.hasCode("itemNotFound") or e.hasCode("ErrorItemNotFound");}
/// Whether a stored delta token has aged out.////// Graph answers a stale `$deltatoken` with 410 Gone and/// `resyncRequired`, which is not an error to retry: it means the incremental/// path is unavailable and the folder has to be listed in full. `Client`/// turns this into `error.ResyncRequired` rather than folding it in with/// every other 410.pub fn isResyncRequired(e: *const ApiError, status: std.http.Status) bool { if (e.hasCode("resyncRequired")) return true; if (e.hasCode("SyncStateNotFound")) return true; return status == .gone;}
pub fn format(e: *const ApiError, w: *std.Io.Writer) std.Io.Writer.Error!void { try w.writeAll(e.code orelse "(no code)"); if (e.message) |m| try w.print(": {s}", .{m}); // Only when it says something the outer code did not, which is most of the // time but not when the inner code is the status repeated. if (e.mostSpecificCode()) |specific| { const outer = e.code orelse ""; if (!std.ascii.eqlIgnoreCase(specific, outer)) try w.print(" [{s}]", .{specific}); } if (e.request_id) |id| try w.print(" (request-id {s})", .{id});}
const testing = std.testing;
test "the shape the throttling reference documents" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"TooManyRequests", \\ "innerError":{"code":"429","date":"2020-08-18T12:51:51", \\ "message":"Please retry after", \\ "request-id":"94fb3b52-452a-4535-a601-69e0a90e3aa2","status":"429"}, \\ "message":"Please retry again later."}} ); defer e.deinit();
try testing.expectEqualStrings("TooManyRequests", e.code.?); try testing.expectEqualStrings("Please retry again later.", e.message.?); try testing.expectEqual(@as(usize, 1), e.inner.len); try testing.expectEqualStrings("429", e.inner[0].code.?); // Lifted off the inner error, which is where Graph puts it. try testing.expectEqualStrings("94fb3b52-452a-4535-a601-69e0a90e3aa2", e.request_id.?); try testing.expectEqualStrings("2020-08-18T12:51:51", e.date.?);
try testing.expect(e.isRetryable(.too_many_requests)); try testing.expect(!e.isAuthFailure(.too_many_requests));}
test "the shape the error resource type documents, lowercase spelling and all" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"badRequest", \\ "message":"Uploaded fragment overlaps with existing data.", \\ "innererror":{"code":"invalidRange"}, \\ "details":[{"code":"invalidRange","message":"bad","target":"range"}]}} ); defer e.deinit();
try testing.expectEqualStrings("badRequest", e.code.?); // `innererror` and `innerError` are both Graph's own spelling. try testing.expectEqualStrings("invalidRange", e.inner[0].code.?); try testing.expectEqualStrings("invalidRange", e.mostSpecificCode().?); try testing.expectEqual(@as(usize, 1), e.details.len); try testing.expectEqualStrings("range", e.details[0].target.?); try testing.expect(!e.isRetryable(.bad_request));}
test "the most specific code is the deepest one" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"generalException", \\ "innerError":{"code":"middle", \\ "innerError":{"code":"ErrorInvalidIdMalformed"}}}} ); defer e.deinit();
try testing.expectEqual(@as(usize, 2), e.inner.len); try testing.expectEqualStrings("ErrorInvalidIdMalformed", e.mostSpecificCode().?); // And the whole chain is searchable, not only the ends. try testing.expect(e.hasCode("middle")); try testing.expect(e.hasCode("generalException")); try testing.expect(!e.hasCode("something else"));}
test "codes are matched whatever Graph capitalised them as" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"tooManyRequests"}} ); defer e.deinit(); // Graph ships `TooManyRequests` here and `badRequest` there; matching // exactly is the bug that works in a test and not in production. try testing.expect(e.hasCode("TooManyRequests")); try testing.expect(e.hasCode("TOOMANYREQUESTS")); try testing.expect(e.isRetryable(.ok));}
test "everything is optional" { var e: ApiError = try .parse(testing.allocator, "{\"error\":{}}"); defer e.deinit(); try testing.expectEqual(@as(?[]const u8, null), e.code); try testing.expectEqual(@as(?[]const u8, null), e.message); try testing.expectEqual(@as(usize, 0), e.inner.len); try testing.expectEqual(@as(usize, 0), e.details.len); try testing.expectEqual(@as(?[]const u8, null), e.mostSpecificCode()); try testing.expect(!e.hasCode("anything"));}
test "not this shape" { try testing.expectError(error.NotAnError, ApiError.parse(testing.allocator, "<html>502</html>")); try testing.expectError(error.NotAnError, ApiError.parse(testing.allocator, "")); try testing.expectError(error.NotAnError, ApiError.parse(testing.allocator, "{}")); try testing.expectError(error.NotAnError, ApiError.parse(testing.allocator, "[1,2,3]")); // The OAuth shape, which the Microsoft *login* endpoints send and which // `oidc.ErrorResponse` reads: `error` is a string there, not an object. try testing.expectError( error.NotAnError, ApiError.parse(testing.allocator, "{\"error\":\"invalid_grant\"}"), );}
test "an auth or permission failure is never something to wait out" { // Found by `tests/fuzz.zig`: a body carrying a throttling code, arriving // with a status that means the token is the problem. The two predicates // must not both be true, because a caller branches on them in order and // waiting is the one thing that cannot help here. var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"TooManyRequests","message":"Please retry again later."}} ); defer e.deinit();
try testing.expect(e.isAuthFailure(.unauthorized)); try testing.expect(!e.isRetryable(.unauthorized)); try testing.expect(!e.isRetryable(.forbidden)); // And with a status that is not decisive, the code still counts. try testing.expect(e.isRetryable(.too_many_requests)); try testing.expect(e.isRetryable(.ok));}
test "a permission failure is not retried and is not an auth failure" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"ErrorAccessDenied", \\ "message":"Access is denied. Check credentials and try again."}} ); defer e.deinit();
// 403 in Graph is permission and licensing, never quota -- which is the // difference from Google, where a 403 may mean "slow down". try testing.expect(!e.isRetryable(.forbidden)); try testing.expect(e.isPermissionFailure(.forbidden)); try testing.expect(!e.isAuthFailure(.forbidden));}
test "an expired token is recognised" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"InvalidAuthenticationToken", \\ "message":"Access token has expired or is not yet valid.", \\ "innerError":{"code":"CompactToken parsing failed with error code: 80049217"}}} ); defer e.deinit();
try testing.expect(e.isAuthFailure(.unauthorized)); try testing.expect(!e.isRetryable(.unauthorized)); // Recognised from the code alone, for a gateway that rewrote the status. try testing.expect(e.isAuthFailure(.bad_request));}
test "a stale delta token asks for a resync" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"resyncRequired","message":"Resync required."}} ); defer e.deinit(); try testing.expect(e.isResyncRequired(.gone)); try testing.expect(e.isResyncRequired(.ok)); // And it must not be mistaken for something to wait out. try testing.expect(!e.isRetryable(.gone));}
test "the server-error classes are waited out" { for ([_]std.http.Status{ .internal_server_error, .service_unavailable, .gateway_timeout }) |status| { var e: ApiError = try .parse(testing.allocator, "{\"error\":{\"code\":\"generalException\"}}"); defer e.deinit(); try testing.expect(e.isRetryable(status)); } var e: ApiError = try .parse(testing.allocator, "{\"error\":{\"code\":\"itemNotFound\"}}"); defer e.deinit(); try testing.expect(!e.isRetryable(.not_found)); try testing.expect(e.isNotFound(.not_found));}
test "an innerError chain deeper than the cap is truncated, not fatal" { var buf: std.ArrayList(u8) = .empty; defer buf.deinit(testing.allocator);
const depth = max_inner_depth + 10; try buf.appendSlice(testing.allocator, "{\"error\":{\"code\":\"top\""); for (0..depth) |_| { try buf.appendSlice(testing.allocator, ",\"innerError\":{\"code\":\"x\""); } for (0..depth) |_| try buf.appendSlice(testing.allocator, "}"); try buf.appendSlice(testing.allocator, "}}");
var e: ApiError = try .parse(testing.allocator, buf.items); defer e.deinit(); try testing.expectEqual(max_inner_depth, e.inner.len); try testing.expectEqualStrings("top", e.code.?);}
test "formats" { { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"ErrorItemNotFound","message":"The specified object was not found.", \\ "innerError":{"code":"ErrorItemNotFound","request-id":"abc-123"}}} ); defer e.deinit();
var buf: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try e.format(&w); // The inner code repeats the outer one, so it is not printed twice. try testing.expectEqualStrings( "ErrorItemNotFound: The specified object was not found. (request-id abc-123)", w.buffered(), ); } { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":"generalException","message":"An error occurred.", \\ "innerError":{"code":"ErrorInvalidIdMalformed"}}} ); defer e.deinit();
var buf: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try e.format(&w); try testing.expectEqualStrings( "generalException: An error occurred. [ErrorInvalidIdMalformed]", w.buffered(), ); }}
test { _ = json;}