본문 바로가기

Spring

Spring boot thymeleaf 로 Error페이지 처리

728x90
반응형
🔍 모든 에러를 다 잡아낼 수 없기 때문에 Spring에서 ErrorController를 구현해서 에러페이지를 처리할 수 있다.
package org.springframework.boot.web.servlet.error;

import org.springframework.stereotype.Controller;

/**
 * Marker interface used to identify a {@link Controller @Controller} that should be used
 * to render errors.
 *
 * @author Phillip Webb
 * @author Scott Frederick
 * @since 2.0.0
 */
public interface ErrorController {

}

@Controller가 설정된 곳에서 사용이 가능하다. error를 렌더링 해준다.

물론 @RestController도 가능하다.

 

 

🙏 Gradle > thymeleaf추가 

 

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'

타임리프는 잘 안써봐서 모른다. 

 

 

🔘 ErrorController 구현

@Slf4j
@Controller
public class CommonErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        model.addAttribute("code", status.toString());
        model.addAttribute("msg", HttpStatus.valueOf(Integer.valueOf(status.toString())));
        return "error/error";
    }

}

error page 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>ERROR</title>
    <div>
        <h1>Error Page</h1>
        error code : <span th:text="${code}"></span>
        <br>error msg : <span th:text="${msg}"></span>
    </div>

</head>
<body>

</body>
</html>

 


🙋 조금 더 고도화를 하자면..

@Slf4j
@Controller
public class CommonErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, HttpServletResponse response,  Model model) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        int statusCode = Integer.parseInt(status.toString());
        response.setStatus(statusCode);

        model.addAttribute("code", status.toString());
        model.addAttribute("msg", HttpStatus.valueOf(Integer.valueOf(status.toString())));
        return "error/error";
    }

}

CommonErrorController로 들어오는 에러를 잡아서 HttpServletResponse의 status로 세팅한 후 

리턴해 줄 수 있다.

404 Not_found custom이 가능하다. 

728x90
반응형