title: Try catch block in express
body: <p>I google for it and found some examples (like <a href="https://dev.to/nedsoft/central-error-handling-in-express-3aej" rel="nofollow noreferrer">this</a>).</p>
  
  <p>I done everything like there, and all just fine! </p>
  
  <p>But now every my router function contains try...catch block. Like that:</p>
  
  <pre><code>accounts = express.Router()
  
  accounts.post('/following', async (req, res, next) =&gt; {
      try {
          ***do some stuff***
          if (smth_bad)
              next(new ErrorHandler(413, 400, "Wrong data"));
  
      } catch (e) {
          next(e)
      }
  });
  
  accounts.post('/followers', async (req, res, next) =&gt; {
      try {
          ***do some stuff***
          if (smth_bad)
              next(new ErrorHandler(413, 400, "Wrong data"));
      } catch (e) {
          next(e)
      }
  });
  
  
  accounts.post('/posts', async (req, res, next) =&gt; {
      try {
          ***do some stuff***
          if (smth_bad)
              next(new ErrorHandler(413, 400, "Wrong data"));
      } catch (e) {
          next(e)
      }
  });
  
  accounts.post('/pizza', async (req, res, next) =&gt; {
      try {
          ***do some stuff***
          if (smth_bad)
              next(new ErrorHandler(413, 400, "Wrong data"));
      } catch (e) {
          next(e)
      }
  });
  
  app.use('/api/v1/account', accounts);
  
  app.use((err, req, res, next) =&gt; {
      handleError(err, res);
  });
  </code></pre>
  
  <p>I know, that i can use next() without try...catch, but I want to handle unexpected errors and tell about it to user. My handling looks like this:</p>
  
  <pre><code>class ErrorHandler extends Error {
      constructor(statusCode, httpStatus, message) {
          super();
          this.statusCode = statusCode;
          this.httpStatus = httpStatus;
          this.message = message;
      }
  }
  
  const handleError = (err, res) =&gt; {
      if(err instanceof ErrorHandler){
          const { statusCode, message, httpStatus } = err;
          res.status(httpStatus).json({
              status: "error",
              statusCode,
              message
          });
      } else {
          console.error(err);
          res.status(500).json({
              status: "error",
              statusCode: '510',
              message: 'Server error',
          });
      }
  
  };
  </code></pre>
  
  <p>Is there a way to simplify try...catch blocks in every router? </p>