333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
'use strict';
 
const http = require('http');
const fs = require('fs');
const onerror = require('koa-onerror');
const ErrorView = require('./lib/error_view');
const {
  isProd,
  detectStatus,
  detectErrorMessage,
  accepts,
} = require('./lib/utils');
 
module.exports = app => {
  // logging error
  const config = app.config.onerror;
  const viewTemplate = fs.readFileSync(config.templatePath, 'utf8');
 
  app.on('error', (err, ctx) => {
    ctx = ctx || app.createAnonymousContext();
    if (config.appErrorFilter && !config.appErrorFilter(err, ctx)) return;
 
    const status = detectStatus(err);
    // 5xx
    if (status >= 500) {
      try {
        ctx.logger.error(err);
      } catch (ex) {
        app.logger.error(err);
        app.logger.error(ex);
      }
      return;
    }
 
    // 4xx
    try {
      ctx.logger.warn(err);
    } catch (ex) {
      app.logger.warn(err);
      app.logger.error(ex);
    }
  });
 
  const errorOptions = {
    // support customize accepts function
    accepts() {
      const fn = config.accepts || accepts;
      return fn(this);
    },
 
    html(err) {
      const status = detectStatus(err);
      const errorPageUrl = typeof config.errorPageUrl === 'function'
        ? config.errorPageUrl(err, this)
        : config.errorPageUrl;
 
      // keep the real response status
      this.realStatus = status;
      // don't respond any error message in production env
      if (isProd(app)) {
        // 5xx
        if (status >= 500) {
          if (errorPageUrl) {
            const statusQuery =
              (errorPageUrl.indexOf('?') > 0 ? '&' : '?') +
              `real_status=${status}`;
            return this.redirect(errorPageUrl + statusQuery);
          }
          this.status = 500;
          this.body = `<h2>Internal Server Error, real status: ${status}</h2>`;
          return;
        }
        // 4xx
        this.status = status;
        this.body = `<h2>${status} ${http.STATUS_CODES[status]}</h2>`;
        return;
      }
      // show simple error format for unittest
      if (app.config.env === 'unittest') {
        this.status = status;
        this.body = `${err.name}: ${err.message}\n${err.stack}`;
        return;
      }
 
      const errorView = new ErrorView(this, err, viewTemplate);
      this.body = errorView.toHTML();
    },
 
    json(err) {
      const status = detectStatus(err);
      let errorJson = {};
 
      this.status = status;
      const code = err.code || err.type;
      const message = detectErrorMessage(this, err);
 
      if (isProd(app)) {
        // 5xx server side error
        if (status >= 500) {
          errorJson = {
            code,
            // don't respond any error message in production env
            message: http.STATUS_CODES[status],
          };
        } else {
          // 4xx client side error
          // addition `errors`
          errorJson = {
            code,
            message,
            errors: err.errors,
          };
        }
      } else {
        errorJson = {
          code,
          message,
          errors: err.errors,
        };
 
        if (status >= 500) {
          // provide detail error stack in local env
          errorJson.stack = err.stack;
          errorJson.name = err.name;
          for (const key in err) {
            if (!errorJson[key]) {
              errorJson[key] = err[key];
            }
          }
        }
      }
 
      this.body = errorJson;
    },
 
    js(err) {
      errorOptions.json.call(this, err, this);
 
      if (this.createJsonpBody) {
        this.createJsonpBody(this.body);
      }
    },
  };
 
  // support customize error response
  [ 'all', 'html', 'json', 'text', 'js' ].forEach(type => {
    if (config[type]) errorOptions[type] = config[type];
  });
  onerror(app, errorOptions);
};