From b3a3a660684b17bee116fcf1cc7dae1e85a5ce8a Mon Sep 17 00:00:00 2001 From: jaina heartles Date: Sun, 10 Jul 2022 17:48:54 -0700 Subject: [PATCH] Handle not found errors better --- src/main/db.zig | 5 +++-- src/main/main.zig | 17 ++++++++++------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/main/db.zig b/src/main/db.zig index 19fe72d..1fd2730 100644 --- a/src/main/db.zig +++ b/src/main/db.zig @@ -55,8 +55,9 @@ pub const Database = struct { return db; } - pub fn getNote(self: *Database, id: Id, alloc: std.mem.Allocator) !models.Note { - return try clone(alloc, self.notes.get(id).?); + pub fn getNote(self: *Database, id: Id, alloc: std.mem.Allocator) !?models.Note { + const note = self.notes.get(id) orelse return null; + return try clone(alloc, note); } }; diff --git a/src/main/main.zig b/src/main/main.zig index 30deb06..6d9fd5c 100644 --- a/src/main/main.zig +++ b/src/main/main.zig @@ -28,14 +28,14 @@ const json_options = if (builtin.mode == .Debug) }; // Responds to a request with a json value -fn respondJson(ctx: *http.server.Context, value: anytype, alloc: std.mem.Allocator) !void { +fn respondJson(ctx: *http.server.Context, status: http.Status, value: anytype, alloc: std.mem.Allocator) !void { var headers = http.Headers.init(alloc); defer headers.deinit(); // Don't need to free this k/v pair because they aren't dynamically allocated try headers.put("Content-Type", "application/json"); - var stream = try ctx.openResponse(&headers, .ok); + var stream = try ctx.openResponse(&headers, status); defer stream.close(); const writer = stream.writer(); @@ -45,15 +45,15 @@ fn respondJson(ctx: *http.server.Context, value: anytype, alloc: std.mem.Allocat } fn getNote(srv: *RequestServer, ctx: *http.server.Context, args: RouteArgs) !void { - const id = args.get("id").?; - const note = try srv.db.getNote(id, srv.alloc); + const id = args.get("id") orelse return error.NotFound; + const note = (try srv.db.getNote(id, srv.alloc)) orelse return error.NotFound; defer db.free(srv.alloc, note); - try respondJson(ctx, note, srv.alloc); + try respondJson(ctx, .ok, note, srv.alloc); } fn healthcheck(srv: *RequestServer, ctx: *http.server.Context, _: RouteArgs) !void { - try respondJson(ctx, .{ .status = "ok" }, srv.alloc); + try respondJson(ctx, .ok, .{ .status = "ok" }, srv.alloc); } const RequestServer = struct { @@ -79,7 +79,10 @@ const RequestServer = struct { var ctx = srv.accept(alloc) catch unreachable; defer ctx.close(); - router.dispatch(self, &ctx, ctx.request.method, ctx.request.path) catch unreachable; + router.dispatch(self, &ctx, ctx.request.method, ctx.request.path) catch |err| switch (err) { + error.NotFound, error.RouteNotApplicable => respondJson(&ctx, .not_found, .{ .@"error" = "Not Found" }, alloc) catch unreachable, + else => unreachable, + }; } } };