jingouli

express: 

 

var express=require(\'express\');
var app=express();

// 异常处理
app.use((req,res,next)=>{
    try{
        next();
    }catch(ex){
        res.send(ex.message);
    }
})


app.use((req,res,next)=>{
    console.log(1);     // 1
    next();             // 2
    console.log(2);     // 5  执行时机不确定,与是否异步有关
});

app.use((req,res,next)=>{
    console.log(3);     // 3
    new Promise(resolve=>{  // 4
        setTimeout(resolve,300);
    }).then(()=>{
        next();         // 6
        console.log(4); // 8
    })
});

app.use((req,res)=>{
    // 7
    try{
        res.send(\'Hello World\');
        throw new Error(\'hehe\');
    }catch(ex){
        // 异常处理
    }
});

app.listen(3000);

 

 

 

 

koa:

 

const Koa=require(\'koa\');
const app=new Koa();

// 异常处理
app.use(require(\'./koa-error\'));

process.on(\'unhandledRejection\',err=>{
    console.error(`unhandledRejection: ${err.message}, stack: ${err.stack}`);
});

process.on(\'uncaughtException\',err=>{
    console.error(`uncaughtException: ${err.message}, stack: ${err.stack}`);
})

app.use(async (ctx,next)=>{
    console.log(1);     // 1
    next();             // 2  -----以next为分界线,会先执行next之前的方法,再执行next之后的方法
    console.log(2);     // 8  
});

app.use(async (ctx,next)=>{
    console.log(3);     // 3
    await new Promise(resolve=>{
        setTimeout(resolve,300);
    });     // 4

    await next();       // 5
    console.log(4);     // 7
});

app.use(async (ctx,next)=>{
    ctx.body=\'hello world\';
});

app.listen(3000);

 

分类:

技术点:

相关文章:

  • 2021-10-13
  • 2021-10-03
  • 2021-08-15
  • 2021-10-03
  • 2021-10-03
  • 2021-10-03
  • 2021-10-03
  • 2021-08-15
猜你喜欢
  • 2021-10-03
  • 2021-10-03
  • 2021-07-11
  • 2021-09-26
  • 2021-11-14
  • 2021-10-13
相关资源
相似解决方案