通过显示静态HTML页面进行错误处理 [英] Error Handling by display static HTML page

查看:78
本文介绍了通过显示静态HTML页面进行错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过不仅将消息记录到控制台,而且还将客户端的浏览器重定向到显示一些简单文本内容的静态HTML页面,来向错误处理程序添加功能.这是现有的处理程序:

I am trying to add functionality to my error handler by not only logging the message to the console, but by redirecting the client's browser to a static HTML page that would display some simple text content. Here is the existing handler:

var sql = require('msnodesql');

//store a connection to MS SQL Server-----------------------------------------------------------------------------------
sql.open(connStr, function(err, sqlconn){
    if(err){
        console.error("Could not connect to sql: ", err);

    }
    else
        conn = sqlconn;     //save the sql connection globally for all client's to use
});

我正在使用express.js创建我的Web服务器.这是服务器端代码.我希望这种情况能够实时发生,一旦发生错误,客户端的Web浏览器就会被重定向.

I'm using express.js to create my web server. This is server side code. I want this to happen in realtime, as soon as the error occurs the client's web browser gets redirected.

我想我真正想知道的是如何从 if(err)内部将客户端的浏览器重定向到页面.

I guess what I really want to know is how to redirect the client's browser to a page from inside if(err).

推荐答案

您可以使用中间件来检查每个请求的连接状态,并根据状态呈现适当的模板(而不是使用 res.渲染,您当然也可以使用 res.redirect res.sendfile ):

You can use a middleware that checks the state of the connection for each request and renders an appropriate template depending on the state (instead of using res.render, you can also use res.redirect or res.sendfile, of course):

var sql   = require('msnodesql');
var conn  = null;

sql.open(connStr, function(err, sqlconn) {
  if (err) {
    console.error("Could not connect to sql: ", err);
    conn = false;
  } else {
    conn = sqlconn;
  }
});

// Express middleware that checks the connection state of the database
// connection: active, not yet active, or failed.
app.use(function(req, res, next) {
  // database connection not active yet
  if (conn === null || conn === undefined) {
    res.status(503);
    return res.render('not-active-yet');
  }
  // database connection failed
  if (conn === false) {
    res.status(500);
    return res.render('db-connection-failed');
  }
  // everything seems okay
  next();
});

编辑:忘记提及您需要在中间件链中尽早添加此中间件,但一定要在您的任何路由之前.

forgot to mention that you need to include this middleware very early in the middleware chain, but certainly before any of your routes.

这篇关于通过显示静态HTML页面进行错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆