Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit be829de

Browse files
create ControllerExceptionHandler
1 parent 7d9891f commit be829de

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.csaba79coder.apifirstdevelopment.exception;
2+
3+
import com.csaba79coder.apifirstdevelopment.value.ErrorCode;
4+
import org.springframework.http.HttpStatus;
5+
import org.springframework.http.ResponseEntity;
6+
import org.springframework.web.bind.annotation.ControllerAdvice;
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.apifirstdevelopment.value.ErrorCode.ERROR_CODE_001;
14+
import static com.csaba79coder.apifirstdevelopment.value.ErrorCode.ERROR_CODE_002;
15+
16+
@ControllerAdvice
17+
public class ControllerExceptionHandler {
18+
19+
@ExceptionHandler(value = {NoSuchElementException.class})
20+
public ResponseEntity<Object> handleNoSuchElementException(NoSuchElementException ex) {
21+
return new ResponseEntity<>(responseBodyWithMessage(ERROR_CODE_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(ERROR_CODE_002, ex.getMessage()), HttpStatus.BAD_REQUEST);
27+
}
28+
29+
private String responseBodyWithMessage(ErrorCode code, String message) {
30+
return Map.of(code, message).toString();
31+
}
32+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /