Passed
Pull Request — master (#26)
by lv
02:01
created

internal_error.js ➔ ???   A

Complexity

Conditions 3
Paths 25

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 1
c 0
b 0
f 0
nc 25
rs 10
nop 2
1
//处理内部错误,写错误日志
2
3
const logger = require('./logger.js')
4
const ApiError = require('../util/api_error')
5
6
module.exports = async function (ctx, next) {
0 ignored issues
show
Bug introduced by
The variable async seems to be never declared. If this is a global, consider adding a /** global: async */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
7
	let timeStart = new Date().getTime()
8
	try {
9
10
		await next()
0 ignored issues
show
Bug introduced by
The variable await seems to be never declared. If this is a global, consider adding a /** global: await */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
11
		let timeEnd = new Date().getTime()
12
13
		let req = ctx.request
14
		let res = ctx.response
15
		let fields = {
16
			status: res.status,
17
			accept: req.header['accept'],
18
			cookie: req.header['cookie'],
19
			ua: req.header['user-agent'],
20
			method: req.method,
21
			reqBody: req.body,
22
			url: req.url,
23
			consuminmg: timeEnd - timeStart
24
		}
25
26
		logger.getLogger().trace('success', fields)
27
	} catch (e) {
28
		let status = e.status || 500
29
		let msg = e.message || e
30
		ctx.status = status
31
32
		let req = ctx.request
33
		let res = ctx.response
34
		let timeEnd = new Date().getTime()
35
		let fields = {
36
			status: res.status,
37
			accept: req.header['accept'],
38
			cookie: req.header['cookie'],
39
			ua: req.header['user-agent'],
40
			method: req.method,
41
			reqBody: req.body,
42
			url: req.url,
43
			consuminmg: timeEnd - timeStart
44
		}
45
46
		console.log(fields)
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
47
48
		if (e instanceof ApiError) {
49
			ctx.status = 500;
50
			ctx.body = {
51
				code: e.code,
52
				success: false,
53
				data: [],
54
				message: e.message
55
			}
56
		} else {
57
			console.log(e)
58
			ctx.body = {
59
				code: status,
60
				success: false,
61
				data: [],
62
				msg: msg
63
			}
64
		}
65
		
66
		if (status === 500) {
67
			// 报错在console, 统一使用throw,json返回,不释放 error 事件
68
			// ctx.app.emit('error', e, this)
69
			//写错误日志
70
			logger.getLogger('error').error('error', fields)
71
		}
72
		else {
73
			logger.getLogger('exception').warn('error', fields)
74
		}
75
76
	}
77
}
78
79