gpt4 book ai didi

node.js - 全局异常处理程序无法在node.js中工作

转载 作者:行者123 更新时间:2023-12-03 08:39:48 25 4
gpt4 key购买 nike

如果发生异常,由于未调用错误处理程序,因此请求没有结束。控制台显示错误,但我的消息“内部服务器错误”未发送为
响应。错误块未进入全局处理程序内。

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const rulesRouter = require('./routes/rules');
const lambdasRouter = require('./routes/lambda');

const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(cookieParser());
app.use(express['static'](path.join(__dirname, 'public')));


app.use('/api', rulesRouter);
app.use('/lambda', lambdasRouter);

app.use(function(req, res, next) {
res.status(404).send({
'api_error': {
'dev_msg': 'Resource not available : Not Found',
'user_msg': 'Resource not available',
'user_msg_title': 'Not found!',
'code': 404,
},
});
});

//error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500).send('interal server error');
});



module.exports = app;

最佳答案

您能告诉我们如何发送错误吗?
我们通常会

try {

throw new Error('New error');

} catch(error) {
next(error)
}
这是将错误发送到下一个错误处理中间件的next(error)

关于node.js - 全局异常处理程序无法在node.js中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62754652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com