Handle not found errors better

This commit is contained in:
jaina heartles 2022-07-10 17:48:54 -07:00
parent 470fa50bb1
commit b3a3a66068
2 changed files with 13 additions and 9 deletions

View File

@ -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);
}
};

View File

@ -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,
};
}
}
};