6

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.

1
  • Can you share what documentation you used for the code and how you are planning to implement the error catcher? Commented Mar 9, 2022 at 15:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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); } }) 

1 Comment

I want to handle errors in one common place, because I have many functions. With Express app only, it work well. With express app only, it work well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.