Error Handling — Complete Guide
Error Handling — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MEAN Stack Tutorial on Toolliyo Academy.
On this page
MEAN Stack Tutorial · Lesson 37 of 100
Error Handling
Stack → Projects
Stack · 1 — Pieces · ~6 min · MEAN — Node.js & Express
What is this?
Express error handling centralizes thrown exceptions and rejected promises into consistent JSON responses for MeanVerse clients.
Why should you care?
Scattered try/catch in 80 routes produces inconsistent error shapes and leaked stack traces.
See it live — copy this example
Paste into your MeanVerse project (Angular + Express + MongoDB), then run with ng serve / node / mongosh as noted.
class AppError extends Error {
constructor(public status: number, message: string, public code?: string) {
super(message);
}
}
export function errorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction) {
if (err instanceof AppError) {
return res.status(err.status).json({ code: err.code ?? 'APP_ERROR', message: err.message });
}
console.error(err);
res.status(500).json({ code: 'INTERNAL', message: 'Something went wrong' });
}
// route: throw new AppError(404, 'Account not found', 'ACCOUNT_NOT_FOUND');
What happened?
- AppError carries HTTP status.
- Unknown errors log server-side but return generic 500 — no stack to Angular in production.
Practice next
- Create AppError and errorHandler middleware last in app.use chain.
- Wrap async routes or use express-async-errors.
- Map Mongoose CastError to 400 Bad Request.
- Add ZodError formatter returning field-level errors.
- Integrate Sentry in errorHandler for 500s.
Remember
One error middleware at end of pipeline. Typed AppError for expected failures. Log unexpected 500s for monitoring.
Mobile app error UX
Angular shows field errors from 422 validation response.
Outcome: Standard error JSON powers web and mobile consistently.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!