| Conditions | 3 |
| Paths | 25 |
| Total Lines | 72 |
| Code Lines | 52 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
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:
If many parameters/temporary variables are present:
| 1 | //处理内部错误,写错误日志 |
||
| 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) |
||
|
|
|||
| 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 |