0

I know this is an Anti-Pattern, but in my RESTful application I want to log and throw.

I have this Code

log.warn("Cannot determine provider from name: " + name);
throw X.bad("Cannot determine provider from name: " + name);

This is a situation that shouldn't happen - it is just the last else in a series of if/else if. However in case it does happen it might indicate a front-end bug/error.

  1. My restful stack can deal with exceptions and map them to HTTP responses.
  2. I also want a log entry with a good stacktrace.
  3. I would like the log entry to pertain to the place it was thrown from (I.e. logger category (class name) and stacktrace.

I did think of putting a log.warn(...) inside X.bad() but then the logging class is X and the stacktrace is bigger than it was when the exception was needed to be thrown.

Does anyone have a more integrated solution?

(I think to stop the repetition of the text component more then anything)

Thanks

Rob

2
  • I'm not sure what your question is . . . are you asking if the code you have here will work, if there's a better way to do it, or maybe something else? Commented Mar 20, 2014 at 17:58
  • you are right Scott - I didn't ask any specific. Commented Mar 20, 2014 at 21:31

1 Answer 1

3

there's a 2007 article from Barry Ruzek covering this problem. http://www.oracle.com/technetwork/articles/entarch/effective-exceptions-092345.html

The overall solution is to have a Fault Barrier at the upper layer of your call stack. This Fault Barrier replaces your step 1. It will catch ALL exceptions, and log it accordingly.

I think the thing you didn't check is to create a Custom Exception extending RuntimeException (i.e. MyAppRuntimeException), and add in it the level of log you need to log it, and any other field you would like to transmit to your fault barrier.

Your fault barrier will need also to catch all other exception (Exception, Runtime, etc) an manage them with a default behavior.

You do not need to log before you throw the exception, you only need to log at one place: when you catch the exception with your fault barrier.

If you log the stacktrace, and not only the message, you will still be able to see the root of the problem in your log.

After that, you continue as you do here. Send back the ReST message.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.