Firebase cloud functions catch/handle error

Viewed 204

Update Question: error: TypeError: res.json is not a function

I use Firebase Cloud Functions with Express app. I use middleware for handle error, but it is not working. How to catch/handle error when using throw new Error()?

My code below:

app.get('/test', (req, res) => {
    throw new Error('this is error')
})

function errorHandler(err, req, res, next) {
    res.json({error: err.message}) // error here
}
app.use(errorHandler)

exports.api = functions.https.onRequest(app)

Please help me. Thanks very much.

2 Answers

I had the same issue. You need a try/catch to capture the error and then use the next function to pass it down the middleware chain.

app.get('/test', (req, res, next) => {
    try {
        throw new Error('this is error')
    } catch (err) {
        next(err)
    }
})

function errorHandler(err, req, res, next) {
    res.json({error: err.message}) // error here
}
app.use(errorHandler)

exports.api = functions.https.onRequest(app)

Wrap the whole handler in the try block and it will always pass it down to the error handler.

You can use try/catch to handle error like this:

app.get('/test', (req, res) => {
 try {
      // Your Code
    } catch (e) {
      console.error("error: ", e);
      res.status(500).send(e.message);
    }    
})
Related