What is a good way to pass useful state information to an exception in Java?

前端 未结 11 1869
说谎
说谎 2021-02-04 06:23

I noticed some confusion initially with my question. I\'m not asking about how to configure a logger nor how to use a logger properly, but rather how to capture all of the infor

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 06:49

    You answered your own question. If you want to pass the state to the exception, you need to store your state somewhere.

    You have mentioned adding extra variables to do this, but didn't like all the extra variables. Someone else mentioned a MemoryHandler as a buffer (holds state) between the logger and the application.

    These are all the same idea. Create an object that will hold the state you want you show in your exception. Update that object as your code executes. If an error occurs pass that object into the exception.

    Exceptions already do this with StackTraceElements. Each thread keeps a list of the stack trace (method, file, line) which represents its 'state'. When the exception happens, it passes the stack trace to the exception.

    What you seem to be wanting, is a copy of all the local variables also.

    This would mean making a object to hold all your locals and using that object, instead of the locals directly. Then passing the object to the exception.

提交回复
热议问题