vercel / micro

Asynchronous HTTP microservices

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Intercept standard micro errors

thelinuxlich opened this issue · comments

There should be a event firing inside micro server .catch() to add custom error logic

https://github.com/zeit/micro#error-handling
Specifically this part:

If the error is based on another error that Micro caught, like a JSON.parse exception, then originalError will point to it.

If a generic error is caught, the status will be set to 500.

In order to set up your own error handling mechanism, you can use composition in your handler:

const {send} = require('micro')

const handleErrors = fn => async (req, res) => {
  try {
    return await fn(req, res)
  } catch (err) {
    console.log(err.stack)
    send(res, 500, 'My custom error!')
  }
}

module.exports = handleErrors(async (req, res) => {
  throw new Error('What happened here?')
})

What @timneutkens said! 👌

Why make requests slower with a try-catch when you could expose an event?

@thelinuxlich Events are asynchronous. There's no way to abort a request using an event listener. You can't await an event - that's JavaScript by design.

No need to abort, just a event to plug in a custom logger.

That doesn't really make sense. Throwing an error prevents Node.js from continuing execution. In turn, you NEED to react to the error. If you want to send the error out, however, you can do this:

const {send} = require('micro')

module.exports = async (req, res) => {
  try {
    throw new Error('What happened here?')
  } catch (err) {
    sendErrorAway(err)
    // you could even emit an event here
  }

  send(res, 200, 'everything alright')
}

what if it was programmatic use?