Structured errors help APIs give clear, organized messages when something goes wrong. This makes it easier for developers and users to understand and fix problems quickly.
Why structured errors improve API quality in NestJS
throw new HttpException({
status: HttpStatus.BAD_REQUEST,
error: 'Detailed error message',
code: 'SPECIFIC_ERROR_CODE'
}, HttpStatus.BAD_REQUEST);Use HttpException to create structured error responses in NestJS.
The first argument is an object with details, the second is the HTTP status code.
throw new HttpException({
status: HttpStatus.NOT_FOUND,
error: 'User not found',
code: 'USER_NOT_FOUND'
}, HttpStatus.NOT_FOUND);throw new HttpException({
status: HttpStatus.FORBIDDEN,
error: 'Access denied',
code: 'ACCESS_DENIED'
}, HttpStatus.FORBIDDEN);This NestJS controller throws a structured 404 error when a user is not found. The error includes a status, message, and code for clarity.
import { Controller, Get, Param, HttpException, HttpStatus } from '@nestjs/common'; @Controller('users') export class UsersController { @Get(':id') getUser(@Param('id') id: string) { // Simulate user not found throw new HttpException({ status: HttpStatus.NOT_FOUND, error: 'User not found', code: 'USER_NOT_FOUND' }, HttpStatus.NOT_FOUND); } }
Structured errors make it easier for frontend apps to handle errors predictably.
Always include a clear error message and a unique error code for better debugging.
Consistent error structure improves API maintainability and developer experience.
Structured errors give clear, consistent feedback in APIs.
They help developers and users understand and fix issues faster.
Use NestJS HttpException with detailed objects for best results.
Practice
Solution
Step 1: Understand the role of structured errors
Structured errors give clear, consistent feedback about what went wrong in the API.Step 2: Identify the benefit for clients
Clients get meaningful messages that help them understand and fix issues faster.Final Answer:
They provide consistent and clear error messages for clients. -> Option AQuick Check:
Clear error messages = A [OK]
- Thinking errors speed up the API
- Believing errors hide details always
- Assuming errors fix bugs automatically
Solution
Step 1: Recall NestJS HttpException syntax
HttpException constructor accepts a response object and a status code.Step 2: Identify the correct structured error format
Passing an object with message and status as the first argument is the proper way.Final Answer:
throw new HttpException({ message: 'Error occurred', status: 400 }, 400); -> Option AQuick Check:
HttpException with object and status = A [OK]
- Omitting 'new' keyword
- Passing string only without object
- Using generic Error instead of HttpException
getUser is called with an invalid ID?
import { Controller, Get, Param, HttpException, HttpStatus } from '@nestjs/common';
@Controller('users')
export class UserController {
@Get(':id')
getUser(@Param('id') id: string) {
if (id !== '123') {
throw new HttpException({ error: 'User not found', code: 'USER_404' }, HttpStatus.NOT_FOUND);
}
return { id, name: 'Alice' };
}
}Solution
Step 1: Analyze the error thrown for invalid ID
The code throws HttpException with an object containing error and code, and status 404.Step 2: Understand the client response
The client receives the JSON object with error details and HTTP 404 status.Final Answer:
{ "error": "User not found", "code": "USER_404" } with 404 status -> Option BQuick Check:
Structured error object with 404 = B [OK]
- Expecting plain string instead of object
- Assuming 200 status on error
- Missing error code in response
throw new HttpException('Invalid input', 400);
Why might this be less helpful for API clients?Solution
Step 1: Examine the error thrown
The error is a simple string message without structure.Step 2: Understand impact on API clients
Clients get only a string, missing extra info like error codes or fields.Final Answer:
It throws a string instead of a structured object, limiting error details. -> Option DQuick Check:
String error limits details = C [OK]
- Confusing status code correctness
- Thinking custom classes are mandatory
- Ignoring logging importance here
Solution
Step 1: Understand how to add extra info to errors
Extending HttpException allows customizing the error response object with extra fields.Step 2: Evaluate options for structured error enhancement
Adding timestamp and errorId inside the error object keeps responses consistent and useful for clients.Final Answer:
Extend HttpException to include timestamp and errorId in the response object. -> Option CQuick Check:
Custom HttpException with extra fields = D [OK]
- Thinking console logs affect API response
- Using plain strings loses structure
- Ignoring error details in catch blocks
Ready to prove it?
Pass the test and this pattern moves unknown
