Performance: Why structured errors improve API quality
Structured errors improve API response consistency and reduce client-side parsing overhead, enhancing interaction responsiveness.
throw new HttpException({ status: 'error', code: 'USER_NOT_FOUND', message: 'User does not exist' }, 404);throw new Error('Something went wrong');| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Generic error strings | N/A | N/A | Increases client parsing time | [X] Bad |
| Structured error objects | N/A | N/A | Minimal client parsing overhead | [OK] Good |
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' };
}
}throw new HttpException('Invalid input', 400);
Why might this be less helpful for API clients?Pass the test and this pattern moves unknown