我正在设置一个简单的express.js节点服务器,但似乎无法使我的自定义错误处理程序正常工作。似乎根本没有调用它,而是正在调用一些默认的express.js错误处理程序。
请注意,这很重要,并且使用mongodb(如果认为很重要)。这是相关代码:
index.ts:
import routes from './routes/index.ts';
import express, { Request, Response, NextFunction } from 'express';
// other imports...
type ServerErrror = {
status: number;
message: string;
}
const app = express();
// set up logging...
app.use(bodyParser.json());
app.use('/', routes);
app.use((err: ServerError, req: Request, res: Response, next: NextFunction) => { // eslint-disable-line no-unused-vars
console.error('in error handler');
res.status(err.status).send(`got error: ${err.message}`);
});
mongoose.connect(MONGODB_URI)
.then(() => {
console.log('Successfully connected to database.');
app.listen(SERVER_PORT, () => {
console.log(`Server is up and running on port ${SERVER_PORT}`);
}).on('error', error => {
console.log('Error starting server:', error);
});
}, error => {
console.log('Error connecting to database:', error);
});
routes / index.ts:
import { Router } from 'express';
import dataRoutes from './data.ts';
const router = Router();
router.use('/data', dataRoutes);
export default router;
routes / data.ts:
import { Router } from 'express';
import Data from './models/Data';
const router = Router();
router.get('/', (_, res, next) => {
Data.find((error, data) => {
if (error) {
console.log('found an error')
next({ status: 500, message: 'got an error' });
return;
}
res.send(`Got data: ${JSON.stringify(data.map(datum => datum.toJSON()))}`);
});
});
export default router;
当我启动服务器,然后使用邮递员将GET请求发送到/ data端点时,这是服务器上的输出:
Successfully connected to database.
Server is up and running on port 1234
found an error
GET /data 500 35.289 ms - 142 // this is from morgan logging
[object Object] // no idea where this is coming from, i assume express default error handler
这是我在邮递员中看到的返回值:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>[object Object]</pre>
</body>
</html>
同样,不确定这是哪里来的。我认为它必须是明确的默认错误处理程序。
答案 0 :(得分:2)
您的代码存在一些问题:
import routes from './routes/index.ts'
不应具有*.ts
扩展名。import dataRoutes from './data.ts';
不应具有*.ts
扩展名。ServerErrror
的字母太多。以下是适用于我的计算机的简短示例。我删除了与猫鼬相关的代码,并更改了示例,以便可以在单个文件中轻松复制。调用http://localhost:5000/data
会返回customErrorHandler > dataRoutes.get > Error
,这是您的要求。
import { Request, Response, NextFunction } from 'express';
import bodyParser = require('body-parser');
import express = require('express');
type ServerError = {
status: number;
message: string;
}
const dataRoutes = express.Router().get('/', (_, res, next) => {
setTimeout(() => { // mimic an asynchronous operation
const error = true;
if (error) {
next({ status: 500, message: 'dataRoutes.get > Error' });
return;
}
res.send('dataRoutes.get > Success');
}, 1000);
});
const routes = express.Router().use('/data', dataRoutes);
const app = express();
app.use(bodyParser.json());
app.use('/', routes);
app.use((err: ServerError, req: Request, res: Response, next: NextFunction) => {
res
.status(err.status)
.send(`customErrorHandler > ${err.message}`);
});
app.listen(5000);
console.log('Now listening on port 5000');
这是我的tsconfig.json文件:
{
"compilerOptions": {
"moduleResolution": "node",
"module": "commonjs",
"allowSyntheticDefaultImports": true
}
}
这些是我的package.json依赖项:
"devDependencies": {
"@types/express": "^4.16.1",
"typescript": "^3.4.1"
},
"dependencies": {
"express": "^4.16.4"
}
答案 1 :(得分:1)
事实证明,问题出在我使用babel-preset-minify时,显然无法正确转换代码。摆脱此预设,使代码无需其他修改即可工作。
答案 2 :(得分:0)
就我而言,我禁用了babel-preset-minify选项deadcode
,并且运行良好。
{
"presets": [
[
"minify",
{
"deadcode": false
}
]
]
}