今天在看【新思路管理后台】时遇到了一个很奇怪的问题,函数执行正确的时候系统日志记录是没有问题的,但是函数执行错误的时候,系统日志中的操作者和操作行为不是默认的值,而是上一个正确操作者的信息。这是因为我对日志记录和函数返回其实是封装了一个操作执行类 OperationExecutor
,在多次调用时,某些实例属性(如 opAction
)未能恢复初始值,导致后续调用继承了上一次的状态。本文简单记录一下解决的方案。
这个问题产生的原因其实很简单,因为我在调用操作执行类 OperationExecutor
的时候,只有第一次外部的 opAction
会传入并且进行初始化,后续正常运行过程中初始化的值就不存在了。因此,只需要在最开始时存储初始化的值,并且在每次调用函数的时候,恢复最开始初始化的值就好了。
外部调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const userLoginExecutor = new OperationExecutor({ opFn: async (input) => { const user = await getUser(input) userLoginExecutor.opAction = `${user.id} 账号登录` return user }, opType: "用户操作", opAction: "账号登录" })
await userLoginExecutor.execute({ username: "user1" })
await userLoginExecutor.execute({ username: "user2" })
|
解决方案:
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
| export default class OperationExecutor<InputT = void, OutputT = void> { private readonly initialOpType?: string private readonly initialOpAction?: string
constructor({ opFn, opType, opAction, }: { opFn: (params: InputT) => OutputT | Promise<OutputT> opType?: string opAction?: string }) { this.opFn = opFn this.opType = opType this.opAction = opAction this.initialOpType = opType this.initialOpAction = opAction }
public execute = async (params: InputT): Promise<Result<OutputT>> => { this.opType = this.initialOpType this.opAction = this.initialOpAction return await this.opFn(params) } }
|