Exception Handling
There is always a requirement to handle all the NFR (Non-Functional Requirements) well in any application so that the application performs well in production and possess the excellent traceability and exception reporting mechanisms for better visibility on what happens in applications.
Types of Exceptions
We normally use exceptions within each domain of the application like Customers, Orders, Inventory etc. There are also a lot of custom exceptions that might be required when the application is built to capture, report the exceptions to the user.
In this process, we can follow the below given process
Base Exceptions
There are multiple use-cases where we need separate exceptions to report multiple error conditions or cases, let us consider one such case for data validation.
BaseValidationException
import java.util.List; public class BaseValidationException extends RuntimeException { public BaseValidationException() { super(); } public BaseValidationException(String message) { super(message); } public BaseValidationException(String message, Throwable cause) { super(message, cause); } public BaseValidationException(Listve) { super(String.join(",", ve)); } }
In the above code snippet, we are declaring a BaseValidationException that can be used to report all the entity data validation exceptions in our domain.
Below given is an example of the implementation of this base exception for a product domain
class ProductDataValidationException extends BaseValidationException { public ProductDataValidationException(String message) { super(message); } public ProductDataValidationException(Listve) { super(ve); } public ProductDataValidationException() { super(); } }
Handler advice
In order to report these exceptions that might be getting raised as part of the data validation, we will have to build a advice that can get these exceptions and report in an appropriate manner to the end user. Since these are mainly associated with the data validation, we must report them as a Bad Request with a status code of 404.
import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class GlobalExceptionHandlerAdvice { @ExceptionHandler(BaseValidationException.class) public ResponseEntity<Object> onException(BaseValidationException ex) { return ResponseEntity.badRequest().body(ex.getMessage()); } }
This ensures that any data validation exception that might be thrown by any domain service will be reported as a Bad Request with a status code of 400.
Similar implementations can be done to report other errors with other status codes as well.
Comments
Post a Comment