Common Scenarios
Malformed JSON Handling
If a client sends invalid JSON (e.g., missing brackets or trailing commas), standard Express apps might crash or expose stack traces.ds-express-errors automatically catches SyntaxError from body-parser and returns a clean 400 Bad Request.
Request (Invalid JSON):
POST /users
{ "name": "Alice", } <-- Trailing comma errorImportant
url, stack, method are available in development mode, if you want to change that setting, you can redefine them by setConfig
Response:
{
"status": "error",
"method": "POST",
"url": "/users",
"message": "Unexpected token } ... is not valid JSON",
"stack": ...
}Handling Duplicate Database Entries
When using MongoDB (Mongoose) or Prisma, unique constraint violations (e.g., registering with an existing email) often crash the app or return 500 errors. The library automatically detects these codes (like Mongo's 11000) and converts them to 400 Bad Request.
Controller Code:
import { asyncHandler } from 'ds-express-errors';
// No try-catch needed!
const registerUser = asyncHandler(async (req, res) => {
// If email exists, DB throws error -> Library catches it -> Returns 400
const user = await User.create(req.body);
res.status(201).json(user);
});Response:
{
"status": "fail",
"method": "POST",
"url": "/users",
"message": "Duplicate field value entered: {email:test@example.com}",
"stack": ...
}External Service Failures
When your API acts as a gateway to other services (e.g., Stripe, AWS, or microservices), failures in downstream services should be reported correctly.
Use BadGateway (502) when the upstream service returns an invalid response.
Use ServiceUnavailable (503) when the upstream service is down.
import { Errors } from 'ds-express-errors';
const processPayment = asyncHandler(async (req, res) => {
try {
await stripe.charges.create({...});
} catch (err) {
// Wrap the external error
throw Errors.BadGateway('Payment provider is not responding');
}
});Unsupported Libraries
Handling Unsupported Libraries: Using a library not supported by ds-express-errors? No problem. Use the customMappers config to teach the error handler how to process new error types without waiting for a package update.
