# [TIL] ErrorHandler Middleware

## Issue encountered

When applying the errorHandler middleware and throwing an error with the throw statement inside the try block, the error message thrown in the catch block is being displayed instead of the error message thrown in the throw statement.

## What I tried

To solve this issue, the following steps were taken:

1. The try-catch block was replaced with a Promise and error handling using then() and catch() methods, but this did not provide a fundamental solution as server errors were not being handled properly.
    
2. The issue was identified as being caused by the fact that when a throw statement is used in the try block, it does not immediately pass the error to the middleware but first goes to the catch block before being passed to the middleware.
    
3. To solve this, an if-else statement was added inside the catch block to check if the error message exists and display it (which contains the error information thrown in the try block), and if not, return a 400 error message.
    

```javascript
// GET: List All Posts API
router.get("/", async (req, res) => {
    try {
        const posts = await Posts.findAll({
            order: [["createdAt", "DESC"]],
    });

    if (posts.length === 0)
        throw new Error("404/Posts do not exist.");
        res.status(200).json({ posts });
    } catch (error) {
        throw new Error(error.message || "400/Fail to list posts."); // or operator
    }
});
```

# What I newly learned

1. Sequelize's where object keys in the findOne method are case-insensitive =&gt; "Yes, the keys in the `where` object in Sequelize's `findOne` method are case-insensitive. This means that you can use lowercase or uppercase letters interchangeably for the keys in the `where` object, and Sequelize will treat them as the same."
    
2. `npm install library` vs. `npm install library -S`
    
    * when you run `npm install library -S` or `npm install library --save`, the library is not only installed as a dependency in your project but also saved to your `package.json` file under the "dependencies" section. This means that if you delete your `node_modules` folder and run `npm install` again, the library will be installed automatically based on the `package.json` file.
        
    * In summary, using the `-S` or `--save` flag when installing a library with npm saves it as a dependency in your `package.json` file, making it easier to manage and reproduce the dependencies of your project.
        
3. [How to do Error handling efficiently in Express](https://teamdable.github.io/techblog/express-error-handling#:~:text=%ED%8C%A8%ED%84%B4%EC%B2%98%EB%9F%BC%20%EA%B9%94%EB%81%94%ED%95%B4%EB%B3%B4%EC%9D%B4%EC%A7%80%EB%8A%94%20%EC%95%8A%EC%8A%B5%EB%8B%88%EB%8B%A4.-,express%2Dasync%2Derrors,-express%2Dasync%2Derrors)
    

#### How I used ErrorHandler Middleware

1) First, write the `errorHandling` middleware and import it into the router.

```javascript
module.exports = async (error, req, res, next) => {
  const [status, errorMessage] = error.message.split("/");
  console.error(error);
  return res.status(status).json({ errorMessage });
};
```

2) Since it will be used inside an async function, the `express-async-errors` library was used, which automatically passes the error to the next middleware when encountering `throw new Error()`, so there is no need to call `next()`. Install the library and import it into the `app.js` file.

3) In the router, change the return statements for exception and error cases to throw `new Error("statusCode/errorMessage")` format. (Since `errorHandler` splits the error message by "/", the `error.message` should be written as shown above.)

4) Finally, add the code `router.use(errorHandler)` to use the errorHandler middleware at the end of all router APIs."
