|Express| Express: Handling Errors
Tags: javascript, html, css, webdev
Published: 2020-12-18 20:20:08

---
title: |Express| Express: Handling Errors
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---

                 -Express Built-In Error Handler 
                 -Defining Custom Error Handlers 
                 -Our Custom Error Class 
                 -Handling Async Errors
                 -Handling More Async Errors
                 -Defining An Async Utility 



###Express Built-In Error Handler 
Most of the common errors within an express application may be due to incomplete data, problems connecting or interacting with the database, APIs, external services, and libraries. Also end users may discover unknown bugs within the application by accident or intentional.  


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q7824z9uuls0g2y8sp29.png)

When an error is thrown deliberately or not express is going to catch the error and respond with its own built-in error handling functionality. Express uses a status code 500 by default, however it is possible to change the status code. The error response also includes a stack trace when in developer mode. 

###Defining Custom Error Handlers 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9ufii05jswl4g5ycxzci.png)

There needs to be four functions to writing custom error handlers which are err, req, res, next. Must be put last after all app.use statements within the code. 

```javascript 

app.use(function (err, req, res, next) {
  console.error(err.stack) 
  res.status(500).send('Something broke!') 
})

```

###Our Custom Error Class 
It is necessary to respond to errors with a status code and a response. There are many different ways to achieve the process when working in express. A response can be used with templates to add in more information. 
A common message may be status code error 500 which means something went wrong on the server side. A status code of 401 means unauthorized or not authorized. 



###Handling Async Errors
this code is just for conceptual practice it is not part of an project or application. 

```javascript 

app.get('/products/new', (req, res) => {
   throw new AppError('Not Allowed, 401) 
   res.render('products/new', { categories }) 
})

```

```javascript 
app.use((err, req, res, next) => {
   const {status = 500, message = 'Something went wrong'} = err;
   res.status(status).send(message); 
})
```

```javascript 

app.get('/products/:id', async (req, res) => {
   const { id } = req.params; 
   const product = await Product.findById(id) 
   if (!product) {
        throw new AppError('Product Not Found, 404) 
   }
 res.render('products/show', { product }) 
})

```



###Handling More Async Errors
It is necessary to use try/catch statements for handling async errors. 

this code is just for conceptual practice it is not part of a project or application. 

```
app.post('/products', async (req, res) => {
   try {
     const newProduct = new Product(req.body); 
     await newProduct.save(); 
     res.redirect(`/products/${newProduct._id}`)
  } catch(e) {
    next(e);
}

})


app.get('/products/:id', async (req, res, next) => {
  try {
   const { id } = req.params;
   const product = await Product.findById(id)
   if (!product) {
     throw new AppError('Product Not Found', 404); 
   }
   res.render('/products/show', { product })
} catch (e) {
   next(e);
}
})








```



###Defining An Async Utility 

There is a better way to handle errors other than just using try/catch. Creating functions that wrap the async callbacks that will catch errors. 


```javascript 

function wrapAsync(fn) {
  return function(req, res, next) {
   fn(req, res, next).catch(e => next(e))
  }
} 
```

```
app.get('/products/:id', wrapAsync(async, req, res, next) => {
   const { id } = req.params;
   const product = await Product.findById(id)
   if (!product) {
     throw new AppError('Product Not Found', 404); 
   }
   res.render('/products/show', { product })

}
})


```