今日已更新 305 条资讯 | 累计 19865 条内容
关于我们

Stop Writing try/catch in Every Controller

vedant kale 2026年07月14日 20:28 0 次阅读 来源:Dev.to

When I first started building APIs with Express.js, every async controller looked the same. I would write a try block, perform some database operations, and then write a catch block that called next(error) . It worked, so I copied the same pattern into every controller. One controller became ten. Ten became fifty. Eventually, I realized that half of my controller code wasn't actually business logic, it was just repetitive error handling. That's when I discovered the Async Handler pattern. The Problem A typical Express controller often looks like this: export const getUser = async ( req , res , next ) => { try { const user = await User . findById ( req . params . id ); if ( ! user ) { throw new Error ( " User not found " ); } res . json ( user ); } catch ( error ) { next ( error ); } }; There's nothing wrong with this code. The problem is that every async controller ends up looking exactly the same. Every file contains: try, catch and next(error) over and over again. Besides being repetitive, it's also easy to forget. Miss one try-catch block, and Express won't automatically catch errors thrown inside async functions. What Is an Async Handler? An async handler is a small wrapper function that automatically catches errors from async controllers. Instead of every controller handling its own errors, the wrapper does it for you. A Simple Analogy Imagine an office where every employee has to stop working whenever someone rings the front door. Besides doing their own job, they also have to greet every visitor. This quickly becomes repetitive and inefficient. Instead, the company hires a receptionist to handle every visitor. Now the employees can focus on their actual work while the receptionist takes care of the door. An async handler works the same way. Controllers focus on handling requests, while the async handler catches errors and passes them to Express's error handler. Without an Async Handler export const createUser = async ( req , res , next ) => { try { const user

本文内容来源于互联网,版权归原作者所有
查看原文