node.js - How does exactly Express.js handle errors? -
so, trivial thing. know express has built-in default error handler expect 4 arguments (err, req, res, next) handle "synchronous exceptions" referenceerror, typeerror, etc:
update: question express-specific, not how catch unhandled exceptions/etc. want know how in first code block express can handle user-defined exception. second example async. exception doesn't directly belongs question.
const express = require('express')(); express.all('*', (req, res) => { throw new error('my own error'); res .send('okay?'); }); express.use((err, req, res, next) => { console.error(err.stack); res .status(503) .send('express still , running'); }).listen(3000);
but not this:
const express = require('express')(); express.all('*', (req, res) => { process.nexttick(() => { throw new error('my own error'); }); res .send('okay?'); }); express.use((err, req, res, next) => { console.error(err.stack); res .status(503) .send('won\'t executed'); }).listen(3000);
but i'm curious realization of handler.
i can't find
process.on('uncaughtexception'...
or domains/promises/cluster.
maybe miss something.
can clarify?
there catch-all kind of block in express's router gets executed:
try { fn(req, res, next); } catch (err) { next(err); }
so in block exceptions catched , translated next()
function calls error parameter set match exception.
in more detail, when request arrives express:
app.handle()
called, determines router , callsrouter.handle()
router.handle()
processes through layers , matches handler registeredexpress.all('*', ...)
signaturehandle_request
(inside router's internal layer module) calls handler function specified in above try-catch block, catching possible exceptions , translating them next calls.
Comments
Post a Comment