
ControllerAdvice
: 에러처리를 한다
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class MyControllerAdvice {
@ResponseBody
@ExceptionHandler(RuntimeException.class)
public String err(RuntimeException e){
//StringBuilder builder = new StringBuilder(); // 문자열을 더하는 builder pattern
/**
* springboot는 기본응답 html
*/
String body = """
<script>
alert('${msg}');
history.back();
</script>
""".replace("${msg}",e.getMessage());
return body;
}
}
- @ResponseBody 오류에 대한 응답을 client에게 해줘야하는데 ControllerAdvice는 ViewResolver를 타기 때문에 file을 찾는다. → file로 응답하기에는 file이 너무 많아지기 때문에 JavsScript로 응답하기 위해 @ResponseBoy를 붙여준다.
- @ExceptionHandler(RuntimeException.class) 매개변수만으로 에러의 응답을 찾기 위해서는 reflection에서 for문을 돌려서 매서드의 매개변수를 분석하는데 이 때 reflection의 연산을 줄이기 위해 @ExceptionHandler(RuntimeException.class)를 붙여준다.
RuntimeException 경우의 수 나누기
import com.example.blogv11._core.error.ex.Exception400;
import com.example.blogv11._core.error.ex.Exception404;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class MyControllerAdvice {
@ResponseBody
@ExceptionHandler(Exception400.class)
public String err400(Exception400 e){
System.out.println("error400");
String body = """
<script>
alert('${msg}');
history.back();
</script>
""".replace("${msg}",e.getMessage());
return body;
}
@ResponseBody
@ExceptionHandler(Exception404.class)
public String err404(Exception404 e){
System.out.println("error404");
String body = """
<script>
alert('${msg}');
history.back();
</script>
""".replace("${msg}",e.getMessage());
return body;
}
}
Exception404
: RuntimeException을 상속해 RuntimeException안의 메세지를 보내는 메서드를 구현한다.
public class Exception404 extends RuntimeException {
public Exception404(String msg) {
super(msg);
}
}

Share article