Can I reuse the express.js error view?

前端 未结 1 1628
闹比i
闹比i 2021-01-16 10:17

When express can\'t find a view it errors out and (in debug mode) renders a nice looking page. Is there a convenient way to re-use that view for my own error messages?

相关标签:
1条回答
  • 2021-01-16 10:58

    I don't know how to reuse the view but you can use the error.stack to render the stack trace.

    I have something like this:

    app.all( '*', function(req, res){
      var code = 404;
      res.local('error', { type: 'http', code: code });
      res.local('code', code );
      res.render('errors/index', { status: code } );
    });
    
    app.error(function(err, req, res, next){
    
      var code;
    
      if( err.type === 'http' ){
        code = err.error;
      } 
      else {
        code = 500;
      };
    
      if(err){
        res.local('stack', err.stack || JSON.stringify(err, null, 2) );
      };
    
      res.local('code', code );
      res.render('errors/index', { status: code } );
    
    });
    

    If I need to manually set like a 404 I do the following in my views:

    next( {type:'http', error: 404} );
    

    That's where there is a type check in my views.

    0 讨论(0)
提交回复
热议问题