One Error Shape
Part of the REST APIs section of Coddy's Node.js journey. Lesson 8 of 18.
Your API answers errors in two shapes now: a string for a 404 and zod's object for a 400. A client has to handle each one. Pick one shape for every error:
{ "error": { "code": "not_found", "message": "Invoice not found" } }
{ "error": { "code": "invalid_body", "message": "Too small: ...",
"fields": { "amount": ["Too small: expected number to be >0"] } } }code is for programs: it never changes, so a client can compare it. message is for people, and its wording may change. fields tells a form which input to mark. Write the shape in one function and call it from every route, so no route can drift:
sendError(res, 404, 'not_found', 'Invoice not found');Challenge
Easy- Write
sendErrorinerrors.js:{ "error": { "code", "message" } }with the status, plusfieldsonly when given. - Use it for every 404 (code
not_found),sendInvalidfor every bad body, andsendErrorinserver.js's error handler (invalid_json,server_error).
Send DELETE /api/tasks/99, then POST with { "title": 123 }.
Try it yourself
import { z } from 'zod';
// Sends every error in one shape:
// { "error": { "code": "not_found", "message": "Task not found" } }
// with "fields" added only when it is given.
export const sendError = (res, status, code, message, fields) => {
// Send the answer here
};
// A zod error as a 400: its first problem as the message, each field's
// problems in fields.
export const sendInvalid = (res, zodError) =>
sendError(res, 400, 'invalid_body', zodError.issues[0].message, z.flattenError(zodError).fieldErrors);
This lesson includes a short quiz. Start the lesson to answer it and track your progress.