0
0
Node.jsframework~30 mins

Error response formatting in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Error Response Formatting in Node.js
📖 Scenario: You are building a simple Node.js server that sends error responses in a consistent JSON format. This helps clients understand what went wrong.
🎯 Goal: Create a Node.js server that returns error responses with a JSON object containing status, message, and errorCode fields.
📋 What You'll Learn
Create an error object with specific properties
Add a configuration variable for default error code
Write a function to format the error response JSON
Send the formatted error response in the server
💡 Why This Matters
🌍 Real World
APIs and web servers need to send clear, consistent error messages so clients can handle problems properly.
💼 Career
Understanding error response formatting is essential for backend developers working with Node.js and building reliable web services.
Progress0 / 4 steps
1
Create the error object
Create a constant called error with these exact properties: status set to 400, message set to "Invalid input", and errorCode set to "INVALID_INPUT".
Node.js
Need a hint?

Use const error = { status: 400, message: "Invalid input", errorCode: "INVALID_INPUT" }.

2
Add default error code configuration
Create a constant called DEFAULT_ERROR_CODE and set it to the string "UNKNOWN_ERROR".
Node.js
Need a hint?

Use const DEFAULT_ERROR_CODE = "UNKNOWN_ERROR"; to set the default error code.

3
Write the error formatting function
Write a function called formatErrorResponse that takes an error object as input and returns a new object with status, message, and errorCode. Use the errorCode from the input error if it exists; otherwise, use DEFAULT_ERROR_CODE.
Node.js
Need a hint?

Use error.errorCode || DEFAULT_ERROR_CODE to provide a fallback error code.

4
Send the formatted error response in a Node.js server
Create a simple Node.js HTTP server using http.createServer. In the request handler, use formatErrorResponse(error) to get the error JSON, set the response header Content-Type to application/json, and send the JSON stringified error response with the status code from error.status.
Node.js
Need a hint?

Use http.createServer and res.writeHead with Content-Type set to application/json.