0

I used Spring Boot 1.5 which uses Logback.

I created event objects in controllers and validated them using @EventListener. When a validation error happened I raised an ApplicationSpecificException and caught it globally using a @ControllerAdvice @ExceptionHandler. I thought it will make my design cleaner.

The thing is that these kinds of exceptions (which, now that I think about it, are used for control flow) are written in my logs. I am pretty sure I don't need them so I am creating a filter to ignore them. Is this a design smell of using exceptions in an non appropriate way?

One thing I can do is to catch exceptions in my controller before they propagate to my global exception handlers, but still exceptions are used as control flow mechanism (between event listeners and controllers).

Any other suggestions? Am I doing sth really wrong here? Should I refactor my code to return booleans? I can recall at Clean Code states "Use Exceptions Rather Than Return Codes" if it makes you code cleaner. Thanks

Nikos
  • 265
  • 2
  • 6
  • 1
    Possible duplicate of [Are exceptions as control flow considered a serious antipattern? If so, Why?](https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why) – gnat Jun 12 '17 at 20:32
  • Personally I consider using exceptions for validations a code smell. – Justin Jun 12 '17 at 22:48

1 Answers1

2

Throwing when validation fails is good and it is not regarded flow control. It is rather aborting the normal flow due to an exceptional condition being met, one that inhibits your code to proceed. Thus an exception is appropriate.

This type of exception should not reach you global handler though, only unexpected exceptions should end up there and be logged. So yes, you should catch it earlier in a catch clause that tests for this type specifically.

Martin Maat
  • 18,218
  • 3
  • 30
  • 57