我一直在尝试使用 try 和 catch 以及创建一个单独的文件在异步函数上实现 Express 中的错误处理,但是当我得到错误时 express 无法处理它,站点就会崩溃。
我已经在 app.get('/campgrounds/:id...
JS文件:
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const Campground = require('./modules/campground');
const engine = require('ejs-mate');
const methodOverride = require('method-override');
const cities = require('./seeds/cities')
const ExpressError = require('./utilities/ExpressError');
const catchAsync = require('./utilities/catchAsync');
mongoose.connect('mongodb://localhost:27017/yelpcamp');
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const app = express();
app.engine('ejs', engine);
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
app.use(express.urlencoded({extended:true}));
app.use(methodOverride('_method'));
app.get('/',(req,res)=>{
res.redirect('/campgrounds');
})
app.get('/campgrounds',catchAsync(async (req,res)=>{
const campgrounds = await Campground.find({});
res.render('campgrounds/index',{campgrounds})
}))
app.get('/campgrounds/new',catchAsync(async (req,res)=>{
const campgrounds = await Campground.find({});
res.render('campgrounds/new',{ campgrounds })
}))
app.post('/campgrounds',catchAsync(async(req,res, next)=>{
const newCampground = new Campground(req.body);
await newCampground.save();
res.redirect(`campgrounds/${newCampground._id}`);
}))
app.patch('/campgrounds/:id', catchAsync(async (req,res)=>{
const {id}=req.params;
const campground = await Campground.findByIdAndUpdate(id, req.body, {runValidators: true, new: true});
res.redirect(`/campgrounds/${id}`)
}))
app.delete('/campgrounds/:id',catchAsync(async (req,res)=>{
const { id } = req.params;
await Campground.findByIdAndDelete(id);
res.redirect('/campgrounds');
}))
app.get('/campgrounds/:id',catchAsync(async (req,res,next)=>{
const { id } = req.params;
const campground = await Campground.findById(id);
res.render('campgrounds/details',{campground})
}))
app.get('/campgrounds/:id/edit',catchAsync(async(req,res)=>{
const { id } = req.params;
const campgrounds = await Campground.find({});
const campground = await Campground.findById(id);
res.render('campgrounds/edit',{campground, campgrounds});
}))
app.use((err,req,res,next)=>{
res.send('Error here!');
})
app.listen(3000,()=>{
console.log('Listening on port 3000')
})
这是名为 catchAsync 的单独文件:
module.exports = func =>{
return (req,res,next) =>{
func(req,res,next).catch(next);
}
}