본문 바로가기

프로그래밍/Spring Boot

Spring Boot_예외 처리 기술 (Exception)

반응형

예외 처리 기술 (Exception)

Exception 처리

@ControllerAdvice Global 예외처리 및
특정 package / Controller 예외처리
@ExceptionHandler 특정 Controller의 예외처리

응답으로 객체를 리턴해줘야 하기 때문에 @RestControllerAdvice를 예외처리 클래스에 꼭 적어줘야 한다.

 

사용자 지정 예외 처리 예제

CustomRestfullException.java

1
2
3
4
5
6
7
8
9
10
11
@Getter
public class CustomRestfullException extends RuntimeException {
    
    private HttpStatus status;
    
    public CustomRestfullException(String message, HttpStatus status) {
        super(message);
        this.status = status;
    }
    
}
cs

→ 유효성 검사를 할 때 예외를 던져주어 : throw new CustomRestfullException(message, status); 사용할 수 있다.

 

 

MyRestfullExceptionHandler.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
@RestControllerAdvice // IoC 대상 + AOP 기반
public class MyRestfullExceptionHandler {
 
    // 모든 예외를 여기서 처리해 준다. 
    @ExceptionHandler(Exception.class
    public void exception(Exception e) {
        System.out.println(e.getClass().getName());
        System.out.println(e.getMessage());
    }
 
    // 위의 CustomRestfullException클래스를 이용해 
    // 사용자 정의 예외 클래스로 활용
    @ExceptionHandler(CustomRestfullException.class
    public String basicException(CustomRestfullException e) {
        StringBuffer sb = new StringBuffer();
        sb.append("<script>");
        // 반드시 마지막에 세미콜론을 붙여야 한다.
        sb.append("alert('" + e.getMessage() + "');");
        sb.append("history.back();");
        sb.append("</script>");
        
        return sb.toString();
    }
 
}
cs

 

 

 

UserController.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
@Controller
@RequestMapping("/user")
public class UserController {
 
   @Autowired 
   private UserService userSevice;
   
   @Autowired
   private HttpSession session;
   
   @PostMapping("/sign-up")
   public String signUpProc(SignUpFormDto signUpFormDto) [
   
       // 유효성 검사
       if (signUpFormDto.getUsername() == null || signUpFormDto.getUsername().isEmpty()) {
           throw new CustomRestfullException("uesrname을 입력해주세요.", HttpStatus.BAD_REQUEST);
       }
       
       if (signUpFormDto.getPassword() == null || signUpFormDto.getPassword().isEmpty()) {
           throw new CustomRestfullException("password를 입력해주세요.", HttpStatus.BAD_REQUEST);
       }
       
       if (signUpFormDto.getFullname() == null || signUpFormDto.getFullname().isEmpty()) {
           throw new CustomRestfullException("fullname을 입력해주세요", HttpStatus.BAD_REQUEST);
       }
       
       // 서비스 호출
       userService.createUser(signUpFormDto);
       
       return "redirect:/user/sign-in";
   
   }
 
}
cs

→ 회원가입시 username, password, fullname이 비어있을 때 사용자에게 예외를 던져줄 수 있다.

반응형