-2

How to design a service layer structure that will be resistant to exceptions. Let's say I have a simple OrderService service, this service performs basic operations - saving an order.

public interface OrderService {
   NewOrderResponse placeOrder (NewOrderRequest request);
}

What I need to do while placing a new order:

  1. Validation (check that NewOrderRequest is valid to be placed)
  2. Request / response logging ("Event ABC took place on the order XYZ")
  3. Notification ("Your order has been sent" etc.)

For my needs I use Decorator design pattern - one for validation, second for logging etc.

I'm wondering how to solve and where to place an exception handling in this structure (it should catch exceptions when particular action was not performed correctly). E.g. an exception may occur when sending an order to the repository (in our case repository implementation throws a checked exceptions).

Question:

Should be exceptions propagated to the top decorator (ex. 4) ExceptionHandlerDecorator) to catch and log exceptions? Or should the OrderService implementation catch and handle own exceptions and do not propagate them to other decorators?

Any idea how to solve it? What is best practice for this situation?

1
  • Why downvoting?
    – Artegon
    Mar 17, 2021 at 16:23

2 Answers 2

1

The question here is not about the Decorator , the question is about the Client of your service which includes the decorator as part of the invocation.

What is the cause of the exception and is the cause externaly significant to the client, or maybe the error is internal for the service .

Example external significance : Your order is not filled in according to business rules. This is externaly significant error situation and the client of the service should be aware that your input is wrong.

Example of internal exception: Your service is invoking another service which execution is optional. In this case even if there is an error which is of external significance it should be reported as part of the response and not as an exception and the exception itself will be logged and consumed.

And the rule of the thumb with regards of exceptions once thrown:

  • A recoverable exception is usualy checked.
  • Unrecoverable exception is unchecked.
0

I think that it very much depends on the exception. Some systems throw named exceptions as a way to error-out. They document exactly what are the exceptions that may be thrown, and services which call them need to anticipate and catch those exceptions while allowing other ones to propagate. "Decorators" might be a convenient way to re-use that sort of logic, but it's not the only way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.