文章加密

;

2021年7月13日 星期二

Is it not possible to stringify an Error using JSON.stringify? The problem is that I end up with an empty object.

 https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify


// String-keyed array elements are not enumerable and make no sense in JSON
let a = ['foo', 'bar'];
a['baz'] = 'quux';      // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]
JSON.stringify(a);
// '["foo","bar"]'

Error object doesn't have its enumerable properties, that's why it prints an empty object



express res 參數說明

https://expressjs.com/zh-tw/api.html#res


res.render的說明

https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/200136/



// ssr error handle基礎框架

export default { // ... hooks: { render: { errorMiddleware(app) { app.use((error, _req, _res, next) => { if (error) { console.log("Logged in errorMiddleware", error); } next(error); }); }, }, }, 

};


// 實際應用

hooks: {
    render: {
      errorMiddleware(app) {
        app.use((errorreqresnext=> {
          // handle ssr error to browser
          if (error) {
            res.writeHead(200, {
              'Content-Length': Buffer.byteLength(JSON.stringify(errorObject.getOwnPropertyNames(error))),  
              'Content-Type': 'text/plain'
            });
              
            res.end(JSON.stringify(errorObject.getOwnPropertyNames(error)));   // Error object doesn't have its enumerable properties, that's why we use replacer. or it'll print an empty object
          } else {
            next(error);
          }

          // setTimeout ok了,timeout就是沒有錯誤而超過時間才會出現,所以直接告訴timeout就可以~~
          res.setTimeout(1000function(){
            // console.log('Request has timed out.');
            res.writeHead(307, {
              Location: '/timeout'
            });
            res.end();
          });
         
        })
      },
    },
  },

沒有留言:

張貼留言