Reputation: 2391
I'm working on an api in Node.js and learned about an option to give my errors one last look before crashing my app...(uncaughtException)
Note: I'm well read at this point on all the reasons some people don't like this feature, so please don't post those concerns here.
The problem I'm experiencing is this:
I create custom error classes for different pieces of code. for instance a Redis_Exception
, which will get thrown in response to errors in my cache layer.
However the following does not bubble up to my uncaughtException function:
throw new Redis_Exception('Some error here');
Instead my app simply prints Redis_Exception: Some error here
to the console. No stack trace as per usual.
Is there some reason that errors thrown in this manner would not bubble up to the top of my applications process?
Upvotes: 0
Views: 2334
Reputation:
An easier way around it, add a middleware with your express server with 4 arguments, 1st argument being the error. This will override the finalhandler handler.
app.use((err, req, res, next) => {
// Similar to uncaughtException handler
// Log error, maybe send it to central server
// Send Custom Log message maybe?
return res.send('Nice server error to user');
}
You should also still keep process.on('uncaughtException', fn);
to handle any uncaught exceptions outside of the http request response pipeline.
Upvotes: 3
Reputation: 2391
Figured out what it is. For some reason express has decided to handle my errors for me.
In this file /node_modules/finalhandler/index.js
on line 67
they basically handle any unhandled errors, which keeps uncaughtErrors from bubbling up to the top of the stack...or down to the bottom. Not really sure which direction this thing is facing.. :D
I added a line to that file and errors starting going through to my exception handler:
66 // unhandled error
67 if (err) {
68 throw err; //my line
I'm not sure how i'm going to move forward knowing this as I don't want to overwrite core functionality, but I'm armed with knowledge now.
UPDATE: After opening tickets with finalhandler and express I got back some info on how to override the default functionality.
The tickets I opened are:
https://github.com/pillarjs/finalhandler/issues/6 https://github.com/strongloop/express/issues/2707
Basically if you wrap your app object in a new http server you can override the last event with your own final function.
var express = require('express')
var http = require('http')
var app = express()
// declare things on app
var server = http.createServer(function (req, res) {
app(req, res, function (err) {
// this is your replacement for finalhandler
})
})
server.listen(3000)
Upvotes: 0