ABOUT ME

Today
Yesterday
Total
  • ExceptionHandler
    백기선(인프런 강의)/더 자바, 코드를 조작하는 다양한 방법 2020. 6. 16. 20:38
    반응형

    스프링 @MVC 예외 처리 방법

    • @ControllerAdvice
    • @ExceptionHandler

     

     

    스프링 부트가 제공하는 기본 예외 처리기

    • BasicErrorController
      • 상속받아 사용
    • HTML과 JSON 응답 지원
    • 커스터마이징 방법
    • ErrorController 구현

     

    커스텀 에러 페이지

    • 상태 코드 값에 따라 에러 페이지 보여주기
    • src/main/resources/static|template/error/
    • 404.html
    • 5xx.html
    • ErrorViewResolver 구현

     

    예제

    public class AppError {
    
    	private String message;
    
    	private String resaon;
    
    	public String getMessage() {
    		return message;
    	}
    
    	public void setMessage(String message) {
    		this.message = message;
    	}
    
    	public String getResaon() {
    		return resaon;
    	}
    
    	public void setResaon(String resaon) {
    		this.resaon = resaon;
    	}
    
    }

     

    @Controller
    public class Samplecontroller {
    
    	@GetMapping("/hello")
    	public String hello() {
    		throw new SampleException();
    	}
    
    	@ExceptionHandler(SampleException.class)
    	public @ResponseBody AppError sampleError(SampleException e) {
    		AppError appError = new AppError();
    		appError.setMessage("error.app.key");
    		appError.setResaon("IDK IDK IDK");
    		return appError;
    	}
    
    }

     

    public class SampleException extends RuntimeException {
    }
    

     

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h1>404</h1>
    </body>
    </html>

     

    프로젝트 구조

     

    반응형
Designed by Tistory.