-2

In the service code at work, we translate certain Exceptions into other exceptions before those exceptions bubble up to our customers. For example, we have code like

catch (FooException e) {
   throw new BarException(e);
}

A team member has his code like

catch (FooException e) {
   throw new BarException(e.getMessage());
}

Is there any difference between the two approaches and how it ultimately affects what Exception our customers see? What's the difference between forwarding just the message of the original exception and forwarding the original Exception object?

Victor Cui
  • 1,393
  • 2
  • 15
  • 35

3 Answers3

4

Is there any difference between the two approaches?

This approach:

throw new BarException(e);

presumably uses the constructor that takes a Throwable cause, which you can get later using getCause() on the newly thrown exception object. This means that you can get the whole of the original exception object that was thrown when you catch the new exception. On the other hand, creating a new exception with the same message (second approach) only gives you the message, and tells you nothing else about the exception that was thrown before this.

Therefore, the first approach can potentially tell you more about the cause of the problem, because you have the whole Throwable object that caused it. You can then get things like the stack trace and stuff from it. This will probably help you trace the problem more.

how it ultimately affects what Exception our customers see?

That depends on what information you display to your customers. If you only display the message, then the customer will only see the message, as well as the type of the cause exception in the first approach, and only the message in the second approach.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
2

Yes, in the first case the original exception is preserved, but in the second case the message of the original exception is being used as the message for the new exception being thrown.

The second case will end up hiding the appropriate details for the actual cause of the issue.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

There is indeed a difference between your approach and your colleagues approach. Your approach where you pass the exception only, will show the exception cause only. And your colleagues approach will show the exception message itself to the customer. If you want to pass both the exception cause & message you can pass both the string & exception like -

    catch (FooException e) {
       throw new BarException(e.getMessage(), e);
    }

You can check the Exception constructor section of the readme of this git project - https://github.com/mscharhag/ET

Mohtasim
  • 111
  • 5