[Middleware]-Standardized Error Handling for API Responses
[Middleware]-Standardized Error Handling for API Responses
This page documents the implementation of a centralized error handler that returns consistent application/problem+json responses for schema validation failures (400) and internal server errors (500) in the AutoExtract Platform.
Implementation is available in branch
js_errorHandlerMiddleware_590761
Related user story: #590761
Summary
Fastify’s built-in validator throws AJV-based errors when incoming requests fail schema validation. By default, these errors do not conform to CLA’s problem+json format. This implementation introduces a global error handler to:
- Intercept validation errors for request body, query, and params
- Return a structured 400 response in the
application/problem+jsonformat - Include a canonical
type,title,status,detail,validationErrors, andinstance - Return consistent 500 responses for internal server exceptions
The handler is scoped to schema-validated routes using POST, PUT, or PATCH and is safe to apply across the platform.
Key Behavior
400 - Invalid JSON Body
Triggered when a request fails schema validation.
Response includes:
type:https://claconnect.com/platform/autoextract/problems/invalid-json-bodytitle:Invalid JSON bodystatus: 400detail: the validation messagevalidationErrors: raw AJV error arrayinstance:/platform/autoextract/<fileId>if available, otherwise/platform/autoextract
Example curl:
Example response:
500 - Internal Server Error
Returned when a controller throws an unhandled error.
Response includes:
type:https://claconnect.com/platform/autoextract/problems/internal-server-errortitle:Internal Server Errorstatus: 500detail: error messageinstance: derived fromfileIdin request body or params
Example curl:
Example response:
Code Additions
1. src/middleware/errorHandler.ts
Centralized error handler registered with Fastify. Detects schema validation failures (AJV) and runtime exceptions and transforms them into problem+json responses.
2. src/index.ts
Registers the error handler early in the server lifecycle.
3. src/routes/index.ts
Adds two test routes for demonstrating 400 and 500 behavior.
4. src/controllers/testController.ts
Controller with two methods: one for successful input, one that throws a 500.
5. src/routes/schemas.ts
Schema definitions for the two test routes.
6. src/types/middleware.ts
Shared type for use in the PUT test route.
Curl Examples

- This implementation is non-invasive and does not interfere with other status codes like 401 or 403
- The
instanceproperty logic can be expanded later to include other request identifiers - All changes are encapsulated and ready for future adoption across more routes or services
