본문 바로가기
TIL: Today I Learned

[TIL] 20201219 Handling Errors in Express Apps

by 김알리 2020. 12. 19.

Express' Built-In Error Handler

  • Responds with default 500 status code
  • HTML response

 

 

Custom Error Handlers

  • Error-handling functions have four arguments (err, req, res, next)
    • Example
app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('Something Broke'); //default error doesn't work anymore.
}
  • If you pass anything to the next() function, Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.
  • If there is no other custom error handler, Express built-in handler is called with next().

 

 

Custom Error Class

Why define an Error Class

  • Generate the error with a particular status code and some message.
  • There are different meanings to the status codes. It's inconvenient to set status code for every situation individually.
  • With custom error class, handling errors can be simplified.
  • Example
class AppError extends Error {
    constructor (message, status) {
        super();
        this.message = message;
        this.status = status;
    }
}

module.exports = AppError; 

What to consider

Default JS error class doesn't have status code(undefined). You can set a default status code to avoid any problems related to this.

 

 

Handling Async Errors

  • For errors returned fro asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them.
  • When something is passed into next(), it runs an error handler.
    • Example
app.get('/product', async (req, res, next) => {
    const product = await Product.findById(id);
    if(!product) {
        return next(new AppError('Product Not Found', 404));
    }
})
  • When handling unintende errors : try/catch
    • Example
app.post('/products', async (req, res, next) => {
    try{
        const newProduct = new Product(req.body);
        await newProduct.save();
    } catch (e) {
        next(e);
    }
})

 

 

Defining Async Utility

  • Using try/catch for every Async function is inconvenient.
  • Define a "wrapAsync" function to catch all the async errors.
    • Example
function wrapAsync(fn) {
    return function (req, res, next) {
        fn(req, res, next).catch(e => next(e))
    }
}

//wrap async callback with this function to avoid adding try/catch
  • Express 5 will be able to handle async funcitons.

 

 

Mongoose Errors

Mongoose Errors have different names. Their types can be singled out with the name.

Ex) ValidatorError, CastError....

 

 

 

 

 

 

* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.