본문 바로가기

express

Error Handling using Promise.

I met some code.

const asyncHandler = fn => (req, res, next) =>
  Promise
    .resolve(fn(req, res, next))
    .catch(next);

 

My express lecture uses this asyncHandler for all of the controller methods. the reason using this 'asyncHandler' is to make code look neat when we do catching errors.

 

My question

1) I wondered how this catch errors??
2) why there's two arrow?
3) why it uses promise??

1) 

Starting with Express 5, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error. For example:

 

2)

this question means you are not familiar with JS and functional programming yet. study js more.

 

3)

same answer with 1). Promise is good to catching error in experss !

 

 


From "http://expressjs.com/en/guide/error-handling.html"

 

Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don't need to write your own to get started.

 

It's important to ensure that Express catches all errors that occur while running route handlers and middleware.

 

Express catches error on the process of route and middleware by itself

For errors returned from asynchronous functions invoked by route handlers and middlware, you must pass them to the next() function, where Express will catch and process them.

app.get('/', function (req, res, next) {
  fs.readFile('/file-does-not-exist', function (err, data) {
    if (err) {
      next(err) // Pass errors to Express.
    } else {
      res.send(data);
    }
  })
})

Starting with Express 5, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error. For example:

app.get('/user/:id', async function (req, res, next) {
  var user = await getUserById(req.params.id)
  res.send(user)
})

// look ! this code doesn't have any next() function !

If getUserById throws an error or rejects, next will be called with either the thrown error or the rejected value. If no rejected value is provieded, next will be called with a default Error object provieded by the Express router.

 

You need to be careful to putting values in next() function(ex, next(anyValue))

If you pass anything to the next() function (except the string 'route'), Express regared the current request as being an error and will skip any remaining non-error handling routing and middleware functions. if the callback has no data, this will work only when error occured.

 

You can use try... catch block to catch errors in the asynchronous code and pass them to Express.

but in the asynchronous code, Express would not catch the error since it is now part of the synchronous hanlder code

"try... catch" block is asynchronous code
Use promises to avoid the overhead of the try... catch block or when using functions that return promises
app.get('/', function (req, res, next) {
  Promise.resolve().then(function () {
    throw new Error('BROKEN');
  }).catch(next) // Errors will be passed to Express.
})

Since promises automatically catch both synchromous errors and rejected promises, you can simply provide next as the final catch hanlder and Express will catch errors, because the catch handler is given the error as the first argument.

 

If you dont like asynchronous code, you can use a chain of handlers to rely on synchronous error catching, by reducing the asynchronous code.

app.get('/', [
  function (req, res, next) {
    fs.readFile('/maybe-valid-file', 'utf-8', function (err, data) {
      res.locals.data = data
      next(err)
    })
  },
  function (req, res) {
    res.locals.data = res.locals.data.split(',')[1]
    res.send(res.locals.data)
  }
])

synchronous error handler catch error by default. !

The default error handler

Express has a built-in error handler that takes care of any erors that might be encountered in the app.

This default error-handling middleware function is added at the end of the middleware function stack.

'express' 카테고리의 다른 글

TOKEN authentication  (0) 2020.05.19
What should I do with Errors? express.js  (0) 2020.05.17
How does HTTP request looks like  (0) 2020.05.15
How do I do object CRUD?  (0) 2020.05.15
UdemyAPI_Define model schema  (0) 2020.05.13