When something goes wrong in a web service, we need a clear way to tell the user what happened. An error response structure helps us send this information in a simple, organized way.
When a user sends wrong data to a web service.
When a requested resource is not found.
When the server has a problem and cannot complete the request.
When the user is not allowed to access certain information.
When the request format is incorrect or missing required parts.
Why might this cause problems in your client code expecting code as a number?
medium
A. Because the error key is misspelled
B. Because the message is missing
C. Because the code is a string, not a number, causing type errors
D. Because the JSON is invalid
Solution
Step 1: Identify the data type of code field
The code field is given as a string "400" instead of a number 400.
Step 2: Understand client expectations
If client expects a number, receiving a string can cause type errors or failed comparisons.
Final Answer:
Because the code is a string, not a number, causing type errors -> Option C
Quick Check:
Type mismatch in code field causes errors [OK]
Hint: Check if code is number, not string, to avoid type errors [OK]
Common Mistakes:
Ignoring type differences
Assuming message is missing
Thinking JSON is invalid
5. You want to design an error response structure that includes an error code, a message, and optionally a list of field errors for validation issues. Which JSON structure below correctly supports this?
Step 1: Understand the need for multiple field errors
We want a list of objects, each with a field name and its error message.
Step 2: Check each option's fields format
{"error": {"code": 422, "message": "Validation failed", "fields": [{"field": "email", "error": "Invalid format"}]}} uses an array of objects with field and error keys, which is clear and extensible.
Step 3: Identify why others are incorrect
{"error": {"code": 422, "message": "Validation failed", "fields": "email: Invalid format"}} uses a string instead of structured data; {"error": {"code": 422, "message": "Validation failed", "fields": {"email": "Invalid format"}}} uses an object but not a list; {"error": {"code": 422, "message": "Validation failed", "fields": ["email", "Invalid format"]}} uses a list mixing field and message without keys.