|
| 1 | +package com.csaba79coder.littersnap.exception; |
| 2 | + |
| 3 | +import com.csaba79coder.littersnap.value.ErrorCode; |
| 4 | +import org.modelmapper.ValidationException; |
| 5 | +import org.springframework.http.HttpStatus; |
| 6 | +import org.springframework.http.ResponseEntity; |
| 7 | +import org.springframework.web.bind.annotation.ExceptionHandler; |
| 8 | + |
| 9 | +import java.util.InputMismatchException; |
| 10 | +import java.util.Map; |
| 11 | +import java.util.NoSuchElementException; |
| 12 | + |
| 13 | +import static com.csaba79coder.littersnap.value.ErrorCode.LS_001; |
| 14 | +import static com.csaba79coder.littersnap.value.ErrorCode.LS_002; |
| 15 | +import static com.csaba79coder.littersnap.value.ErrorCode.LS_003; |
| 16 | + |
| 17 | +public class ControllerExceptionHandler { |
| 18 | + |
| 19 | + @ExceptionHandler(value = {NoSuchElementException.class}) |
| 20 | + public ResponseEntity<Object> handleNoSuchElementException(NoSuchElementException ex) { |
| 21 | + return new ResponseEntity<>(responseBodyWithMessage(LS_001, ex.getMessage()), HttpStatus.NOT_FOUND); |
| 22 | + } |
| 23 | + |
| 24 | + @ExceptionHandler(value = {InputMismatchException.class}) |
| 25 | + public ResponseEntity<Object> handleInvalidInputException(InputMismatchException ex) { |
| 26 | + return new ResponseEntity<>(responseBodyWithMessage(LS_002, ex.getMessage()), HttpStatus.BAD_REQUEST); |
| 27 | + } |
| 28 | + |
| 29 | + @ExceptionHandler(value = {ValidationException.class}) |
| 30 | + public ResponseEntity<Object> handleInvalidPasswordOrUsernameException(ValidationException ex) { |
| 31 | + return new ResponseEntity<>(responseBodyWithMessage(LS_003, ex.getMessage()), HttpStatus.BAD_REQUEST); |
| 32 | + } |
| 33 | + |
| 34 | + private String responseBodyWithMessage(ErrorCode code, String message) { |
| 35 | + return Map.of(code, message).toString(); |
| 36 | + } |
| 37 | +} |
0 commit comments