DEV Community

Safal Bhandari
Safal Bhandari

Posted on

Why your error handling sucks?

-> ๐—ฌ๐—ผ๐˜‚๐—ฟ ๐—ฐ๐—ผ๐—ฑ๐—ฒ ๐˜„๐—ผ๐—ฟ๐—ธ๐˜€ ๐—ฝ๐—ฒ๐—ฟ๐—ณ๐—ฒ๐—ฐ๐˜๐—น๐˜† ๐—ผ๐—ป ๐˜†๐—ผ๐˜‚๐—ฟ ๐—น๐—ฎ๐—ฝ๐˜๐—ผ๐—ฝ. ๐—ฆ๐—ต๐—ถ๐—ฝ๐˜€ ๐˜๐—ผ ๐—ฝ๐—ฟ๐—ผ๐—ฑ๐˜‚๐—ฐ๐˜๐—ถ๐—ผ๐—ป ๐—ผ๐—ป ๐—™๐—ฟ๐—ถ๐—ฑ๐—ฎ๐˜†. ๐—•๐˜† ๐— ๐—ผ๐—ป๐—ฑ๐—ฎ๐˜† ๐—บ๐—ผ๐—ฟ๐—ป๐—ถ๐—ป๐—ด ๐˜†๐—ผ๐˜‚'๐˜ƒ๐—ฒ ๐—ด๐—ผ๐˜ ๐Ÿฑ๐Ÿฌ ๐—ฎ๐—ป๐—ด๐—ฟ๐˜† ๐˜‚๐˜€๐—ฒ๐—ฟ๐˜€, ๐˜‡๐—ฒ๐—ฟ๐—ผ ๐—ฒ๐—ฟ๐—ฟ๐—ผ๐—ฟ ๐—น๐—ผ๐—ด๐˜€, ๐—ฎ๐—ป๐—ฑ ๐—ฎ๐—ฏ๐˜€๐—ผ๐—น๐˜‚๐˜๐—ฒ๐—น๐˜† ๐—ป๐—ผ ๐—ถ๐—ฑ๐—ฒ๐—ฎ ๐˜„๐—ต๐—ฎ๐˜ ๐—ต๐—ฎ๐—ฝ๐—ฝ๐—ฒ๐—ป๐—ฒ๐—ฑ. ๐—ฆ๐—ผ๐˜‚๐—ป๐—ฑ ๐—ณ๐—ฎ๐—บ๐—ถ๐—น๐—ถ๐—ฎ๐—ฟ?

-> Errors aren't exceptionsโ€”they're data. Treat them with the same rigor as your actual data.

I built five layers:

๐—ฆ๐˜๐—ฒ๐—ฝ ๐Ÿญ: ๐—ฆ๐˜๐—ฟ๐˜‚๐—ฐ๐˜๐˜‚๐—ฟ๐—ฒ๐—ฑ ๐—˜๐—ฟ๐—ฟ๐—ผ๐—ฟ ๐—–๐—น๐—ฎ๐˜€๐˜€- Created a custom error class with status codes, operational flags, and debugging details. This captures everything needed for proper error handling in one place.

๐—ฆ๐˜๐—ฒ๐—ฝ ๐Ÿฎ: ๐—˜๐—ฟ๐—ฟ๐—ผ๐—ฟ ๐—›๐—ฎ๐—ป๐—ฑ๐—น๐—ฒ๐—ฟ ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ- Implemented middleware that logs all errors internally. Custom errors return directly to clients. Unexpected errors return generic messages without leaking internals.

๐—ฆ๐˜๐—ฒ๐—ฝ ๐Ÿฏ: ๐—”๐˜€๐˜†๐—ป๐—ฐ ๐—˜๐—ฟ๐—ฟ๐—ผ๐—ฟ ๐—ช๐—ฟ๐—ฎ๐—ฝ๐—ฝ๐—ฒ๐—ฟ - Created a wrapper that catches errors in async routes and passes them to the error handler, preventing crashes.

๐—ฆ๐˜๐—ฒ๐—ฝ ๐Ÿฐ: ๐—”๐˜‚๐˜๐—ต ๐—ฆ๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฐ๐—ฒ - Validates input upfront. Uses generic error messages like "invalid email or password" instead of revealing which users exist. Catches database constraint violations gracefully.

๐—ฆ๐˜๐—ฒ๐—ฝ ๐Ÿฑ: ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ ๐—ฆ๐˜๐—ฎ๐—ฐ๐—ธ - Wired everything in correct order: logging first, routes in the middle, error handling last.

-> ๐—ง๐—ต๐—ฒ ๐—ฅ๐—ฒ๐˜€๐˜‚๐—น๐˜๐˜€

๐—•๐—ฒ๐—ณ๐—ผ๐—ฟ๐—ฒ: Silent failures, no logs, 500 errors crash the app.

๐—”๐—ณ๐˜๐—ฒ๐—ฟ: Clear errors, full context in logs, graceful degradation, error analytics.

Error handling is the difference between a professional app and a hobby project. Implement this pattern now. Your future self at 2 AM will thank you.

๐˜š๐˜ต๐˜ข๐˜ณ๐˜ต ๐˜ต๐˜ฐ๐˜ฅ๐˜ข๐˜บ.

Code for reference: https://lnkd.in/gS9cCTGf

Top comments (0)