Express中间件和异常处理

const express = require('express');
const app = express();

// 中间件的使用
// 中间件校验参数,像java中的过滤器或者拦截器,权限过滤
function valid_params(req,res,next){
    let {name} = req.query;
    if(!name||name.length){
        res.json({
            message:"参数检查失败"
        })
    }else{
        next();
    }
}

// app.all("*",valid_params);
// app级别,比如日志记录请求,每访问一次,记录到数据库等业务
function log_middle_ware(req,res,next){
    console.log("访问来了,记录到数据库");
    next();
}
app.use(log_middle_ware);

app.get("/demo",(req,res)=>{
    res.json({
        name:'huangbaokang'
    })
})

// 自带的static中间件,类似nginx访问静态页
app.use(express.static("static",{
    extensions:['html','htm']
}));

// 第三方中间件,网上学习

// 异常处理
// 程序中抛出的异常,一般做法,使用try-catch语句,在catch里抛出异常,把异常处理交给异常处理器
app.get("/list",(req,res)=>{
    throw new Error("连接数据库失败");
})

function error_handler(err,req,res,next){
    if(err){
        let {message}=err;
        res.status(500).json({
            message:`${message}`
        })
    }else{
        //next();
    }
}
app.use(error_handler);

// 处理404访问异常
function notFound_handler(req,res,next){
    res.status(500).json({
        message:"404 not found"
    })
}
app.use(notFound_handler);



// 运行在8080端口中。
app.listen(8080,()=>{
    console.log("服务启动成功");
})
发布了1184 篇原创文章 · 获赞 272 · 访问量 203万+

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/104216428