학원/SPRING

12/22 70-2 [SPRING] Exception

도원결의 2022. 12. 22. 22:36

Spring에서 예외처리 하는 법

자바랑 비슷하면서도 다름 

 

@ControllerAdvice 어노테이션
 -클래스 위에 붙인다.
  -전역적인 예외처리다.
  -@Service나 @Repository역할을 하는 클래스의 예외 처리는 안된다.
  -클래스의 메소드 위에 @ExceptionHandler를 붙여 예외처리를 실제적으로 한다.
     
   @ExceptionHandler 어노테이션
   -해당 컨트롤러에서 발생하는 예외를 처리할 때 사용. 지역적임
   -@ControllerAdvice보다 우선순위가 높다

 

 

우선 폼

<legend class="w-auto px-3">Spring 예외처리 (${message})</legend>
<form class="form-inline"
    action="<c:url value="/Exception/Exception.do"/>"
    method="post">
    <label>나이</label>
    <input type="text" name="years"	class="form-control mx-2" />
    <input	type="submit" class="btn btn-danger mx-2" value="로그인" />
</form>

 

컨트롤러

 

예외 유형 1

@Controller
public class ExceptionController {

	유형1
	@PostMapping("/Exception/Exception.do")
	public String handler(@RequestParam  String years,Model model) { 
		
 	      // 1. @RequestParam String으로 받을 때 : try~catch로 잡으면 됨 !
		try {  
		model.addAttribute("message","당신의 10년 후 나이는:"+(Integer.parseInt(years)+10));
		}
		catch(NumberFormatException e) {
			model.addAttribute("message","나이는 숫자만..");
		}
		 뷰정보 반환 
		 return "exception13/Exception";

예외유형2

    @ExceptionHandler는 예외처리하려는 모든 컨트롤러마다 작성 해야함
  @ExceptionHandler({Exception1.class,Exception2.class})
  @ExceptionHandler({NumberFormatException.class})

  유형2   
 public String handler(@RequestParam int years,Model model) {
    //2. @RequestParam  int로 받을 때 : 메소드안이 아니라서 try 요거로 못함
                                //@ExceptionHandler 어노로 예외처리한다 

    nullpotintException 발생 테스트용 코드(테스트 시 반드시 숫자를 넣어줘야함 안그럼 여기로 안들어가거든)
    String nullString=null;
    nullString.length();

    model.addAttribute("message","당신의 10년 후 나이는:"+(years+10));
    //뷰정보 반환
    return "exception13/Exception";
}

@ExceptionHandler({NumberFormatException.class})
public String numberFormat(Model model,Exception e) {

    model.addAttribute("message","나이는 숫자만 입력하세요(지역 예외처리)");
    //뷰정보 반환
    return "exception13/Exception";

       
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> nullPointer() {   //ResponseEntity<T> : 이때 T는 응답바디에 쓸 컨텐츠의 타입이다.
    //응답헤더 설정(한글깨짐 방지)
    HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.set("Content-Type","text/plain; charset=UTF-8");
//  ResponseEntity 객체반환  new 연산자
//	return new ResponseEntity<>("널입니다.",httpHeaders, HttpStatus.NOT_EXTENDED);  // 인자 순서 body,headers,status

//	 ResponseEntity 객체반환 메소드 체인 형식
    return ResponseEntity.status(HttpStatus.NOT_EXTENDED).header(HttpHeaders.CONTENT_TYPE,"text/plain; charset=UTF-8").body("널입니다.");

}

 

예외를 한 컨트롤러에서 싹 다 잡아버리기

(개발시에는 에러나는거 확인 해야 하기때문에 잘 안쓰고 배포할 때 사용)

//모든 컨트롤러에서 발생하는 예외를 처리(단,범위 지정 가능) 여기서 싹 다 잡음
//범위  설정을 통해 특정 컨트롤러나 패키지 혹은 타입으로 범위를 제한 할 수 있다.
@ControllerAdvice(basePackages = "com.kosmo.springapp.basic.ajax")  => 설정한 패키지 안에 있는것만 예외잡기(패키지로 제한)
@ControllerAdvice(assignableTypes = {ExceptionController.class})  ==> 타입으로 제한{}요거로 여러 개 넣을 수 있음
@ControllerAdvice ==> 모든 컨트롤러의 예외처리

public class ExceptionControllerAdvice {

	@ExceptionHandler({NumberFormatException.class})
	public String numberFormat(Model model,Exception e) {		
		model.addAttribute("message","나이는 숫자만 입력하세요(전역 예외처리)");
		//뷰정보 반환
		return "exception13/Exception";
	}
}