Skip to content

Commit 8e3fb8b

Browse files
committed
creating a common error handling for RestController with basic error codes (own error handling!)
1 parent 01e470a commit 8e3fb8b

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package com.csaba79coder.littersnap.value;
2+
3+
public enum ErrorCode {
4+
5+
LS_001, LS_002, LS_003
6+
}

0 commit comments

Comments
 (0)