Can I use AuditLog to add information to my exceptions?

33 Views Asked by At

I need to add a specific ID to a CustomException. Unfortunately the ID is hard to get and the only place it appears in my application is when the AuditLogInterceptor grabs the request and extracts it.

Is there a clean way/best practice to get the ID from the AuditRepository or should I leave it completely alone? Since the AuditRepository only persists in-outgoing requests and cleans the event DB, it feels kinda dirty to add a function just to get my information. And a general approach to get any information might be an security issue.

Maybe I could write another service just to intercept responses and extract information if that's possible and clean in any way?

I'm fairly new to spring, so please feel free to educate me if I misunderstood something here completely.

2

There are 2 best solutions below

0
Fuby On BEST ANSWER

I've finally managed to solve my problem.

In the end, I didn't want to touch the AuditLogInterceptor, so I've copied to logic and added a new Interceptor to get the request. There I extracted the ID and added it to the SecurityContextHolder.

I've created a CustomAuthentication which uses the "decorator pattern" to extend the default authentication and giving me the ability to add a new customId field, without changing the current logic.

This approach feels quite clean and secure.

1
Loading On

Three ideas:

when the AuditLogInterceptor grabs the request and extracts it.

Here you can add the id to a static ThreadLocal, which you can access then when you throw the CustomException. But make sure you cleanup the threadlocal after the request is done (finally block for cleanup)


Another solution, which is a bit hacky, is to use the MDC as a kind of Threadlocal. In the interceptor you add the id to the MDC via MDC.put("request-id") and then when you throw the exception you can do MDC.get("request-id") to get the value.


Improving on Idea 2, you can also just add the id to the MDC and just throw an empty CustomException. If you have a nice logging system setup, the request-id appears in all of your logs (even in the stacktrace), because its inside the MDC.

Preferable idea 3 is what i would go for.