Passed
Push — master ( 1adf40...f067da )
by lv
01:05
created

module.exports   B

Complexity

Conditions 3
Paths 25

Size

Total Lines 72
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 52
c 0
b 0
f 0
nc 25
dl 0
loc 72
rs 8.5709
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
//处理内部错误,写错误日志
2
3
const logger = require('./logger.js')
4
const ApiError = require('../util/api_error')
5
6
module.exports = async function (ctx, next) {
7
	let timeStart = new Date().getTime()
8
	try {
9
10
		await next()
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