1.

How do you implement Exception Handling in Spring Boot?

Answer»

The IDEAL approach to implement Exception Handling in Spring Boot is by using @ControllerAdvice annotation. It ALLOWS the multiple scattered @ExceptionHandler to be consolidated into a single global error handling component. It allows full control over the body of the response as well as the status code by use of ResponseEntity. It allows to handle and define the behavior of SEVERAL exceptions in the same class so that there is a common source of all application errors. It also allows to map different errors to the same method if desired.

@ExceptionHandler annotation provides a mechanism for handling and defining behavior for the exceptions thrown during the execution of handlers (Controller OPERATIONS).

@ResponseStatus is used to mark a method or exception with error status code and reason that should be returned to the client. The status code is applied to the HTTP response when the handler method is invoked, or whenever said the exception is thrown.

Example:

ControllerAdvice PUBLIC class ErrorHandler {   @ExceptionHandler(GenericContractException.class)   @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)   public ResponseEntity<ContractError> handleGenericContractException(       final GenericContractException ex) { LOGGER.error("Generic Contract Exception has occurred.");     ContractError cerr = ex.createContractError(); return status(gcex.getRespCode()).body(cerr);   }


Discussion

No Comment Found