Lesson 15 · Node.js on IBM i — From RPG Developer to Modern IBM i Developer
Validate Requests and Return Useful Errors
Give callers predictable 400, 404, 409, and 500 responses without leaking database details.
An API is easier to use when the same kind of problem always produces the same kind of response. It is safer when internal SQL details remain in controlled logs.
Fastify already validates the JSON schemas attached to our routes. A missing toolId, a text value where an integer is expected, or an invalid date should result in HTTP 400 before the database function runs.
Use HTTP status codes deliberately
For this application:
200 Request completed
201 Rental created
400 Request shape or value is invalid
404 Requested record does not exist
409 Request conflicts with current business state
500 Unexpected server failure
Trying to rent an unavailable tool is a conflict, not a server crash. Returning an already completed rental is also a conflict.
Add one error handler
Inside buildServer, after registering the routes, add:
server.setErrorHandler((error, request, reply) => {
if (error.validation) {
return reply.code(400).send({
code: 'INVALID_REQUEST',
message: 'Check the request values and try again.'
});
}
const detail = `${error.message ?? ''} ${error.stack ?? ''}`;
if (detail.includes('75001')) {
return reply.code(409).send({
code: 'TOOL_NOT_AVAILABLE',
message: 'This tool is no longer available.'
});
}
if (detail.includes('75002')) {
return reply.code(409).send({
code: 'CUSTOMER_NOT_ACTIVE',
message: 'This customer cannot begin a new rental.'
});
}
if (detail.includes('75003')) {
return reply.code(409).send({
code: 'RENTAL_ALREADY_CLOSED',
message: 'This rental is not open.'
});
}
if (detail.includes('75004')) {
return reply.code(400).send({
code: 'INVALID_DUE_DATE',
message: 'The due date cannot be in the past.'
});
}
if (error.statusCode >= 400 && error.statusCode < 500) {
return reply.code(error.statusCode).send({
code: 'BAD_REQUEST',
message: 'The request could not be understood.'
});
}
request.log.error({ err: error }, 'Request failed');
return reply.code(500).send({
code: 'INTERNAL_ERROR',
message: 'The request could not be completed.'
});
});
The handler works through the possibilities in order:
- Fastify rejected the request against a route schema. That is a 400.
- Db2 signalled one of the four SQLSTATE values from our procedures. Each becomes a specific 409 or 400. The connector wraps the database message inside its own error, so the handler searches both the message and the stack for the code.
- Fastify itself refused the request for another reason, such as JSON that cannot be parsed. Those errors already carry a 4xx status code, and the handler keeps it rather than reporting a server failure.
- Anything else is unexpected. It is logged in full and the caller receives a plain 500.
Connector error properties can differ by version. On your IBM i, inspect a controlled development error and prefer a documented SQLSTATE property when one is available. The string check above keeps the lesson readable, but production code should not depend on an undocumented message format.
Do not send raw errors to callers
This is tempting during development:
reply.code(500).send(error);
It can reveal schema names, SQL text, IFS paths, package versions, or stack traces. Log the diagnostic information where authorized support staff can reach it, and return a stable public message.
Likewise, do not log complete request bodies by default. A future request may contain personal or sensitive information that should not be copied into operational logs.
Test a few bad requests by hand
curl -i -X POST http://127.0.0.1:3000/rentals \
-H "content-type: application/json" \
-d '{}'
curl -i -X POST http://127.0.0.1:3000/rentals \
-H "content-type: application/json" \
-d '{"toolId":"one","customerId":1,"dueDate":"not-a-date"}'
Both should return 400. Repeating a valid rental for the same tool should return 409.
A request with a past due date should return 400 with INVALID_DUE_DATE.
Manual checks help while learning, but they are easy to forget. The next lesson turns the important behavior into automated tests.
References
Documentation and references used for this lesson.

Comments
Share your thoughts, questions, or real-world IBM i experiences related to this article.