디지털 컨버전스/Spring

[Spring Framework] 예외처리 @ExceptionHandler @ControllerAdvice

gimyeondong 2020. 6. 2. 14:24

예외처리

try - catch 구문 반복

 

Spring의 @ 방식으로 예외처리 하기

 

ExceptionHandler 에서는 throw Exception 하지 않음

 

try-catch 가 ExceptionHandler 보다 우선

 

일괄적으로 처리하고 싶은 것은 @ExceptionHandler로

독자적으로 처리하고 싶은 것만 try-catch


컨트롤러가 여러개 일 경우?

 

ExceptionHandler가 여럿일 수도 있지만

그런경우 예외의 종류가 여러개여야 함

 

예외를 발생시킬 때

숫자의 형태와 관련된 예외 : NumberFormatException

 

컨트롤러로 만들기

 

@ControllerAdvice

모든 컨트롤러에서 발생하는 예외를 일괄 처리

 

package kh.spring.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ExceptionController {
	
	@ExceptionHandler
	public String exceptionHandler(Exception e) {
		e.printStackTrace();
		System.out.println("Exception Handler : 에러가 발생했습니다");
		return "error";
	}
	
	@ExceptionHandler
	public String exceptionHandler(NumberFormatException e) {
		e.printStackTrace();
		System.out.println("NFException Handler : 에러가 발생했습니다");
		return "error";
	}
	
	@ExceptionHandler
	public String exceptionHandler(NullPointerException e) {
		e.printStackTrace();
		System.out.println("NULLException Handler : 에러가 발생했습니다");
		return "error";
	}
	
}