본문 바로가기

프로그래밍/Spring Boot

Spring Boot_예외 처리

반응형

Spring Boot Exception

: 스프링 부트 예외처리 기술 @RestControllerAdvice, @ControllerAdvice

→ @ExceptionHandler(value = 예외클래스이름.class)

 

 

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Data
public class User {
    
    //Gradle 땡겨야 함.
    
    @NotEmpty
    @Size(min = 1, max = 10)
    private String name;
    
    @Min(1)
    @NotNull
    private Integer age;
    
}
cs

 

CustomError.java

1
2
3
4
5
6
7
@Data
public class CustomError {
    
    private String field;
    private String message;
 
}
cs

 

ApiController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@RestController
@RequestMapping("/api")
@Validated 
public class ApiController {
    
    @GetMapping("/test")
    public String test() {
        return "test";
    }
 
    @GetMapping("/user")
    public User get(@Validated @RequestParam String name, @RequestParam Integer age) {
        User user = new User();
        user.setName(name);
        user.setAge(age);
        
        return user;
    }
 
    @PostMapping("/user")
    public User post(@Valid @RequestBody User user) {
        System.out.println(user.toString());
        return user;
    }
 
    @GetMapping("/user2")
    public User get2(@Validated User reqUser) {
        return reqUser;
    }
}
cs

 

GlobalControllerAdvice.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@RestControllerAdvice
public class GlobalControllerAdvice {
    
    //모든 예외 처리
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<?> Exception(Exception e) {
        System.out.println(e.getClass());
        System.out.println(e.getMessage());
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }
 
    //특정 예외 처리
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<CustomError> errorList = new ArrayList<>();
            e.getAllErrors().forEach(error -> {
                String field = error.getCode();
                String message = error.getDefaultMessage();
                CustomError customError = new CustomError();
                customError.setField(field);
                customError.setMessage(message);
                errorList.add(customError);
        });
 
        System.out.println("MethodArgumentNotValidException 잘못된 값을 전달했어");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorList);
    }
 
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public ResponseEntity<?> httpMessageNotReadableException(HttpMessageReadableException e) {
        System.out.println("HttpMessageNotReadableException 아직도 json 형식을 모르니");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
    }
 
}
cs

 

→ 모든 예외 처리와 특정 예외 처리로 나누어 예외를 처리할 수 있다.

 

결과 화면

→ @RestControllerAdvice는 @ResponseBody가 있어서 응답을 Json으로 내려준다.

반응형