본문 바로가기

프로그래밍/Spring

[Spring] ErrorController를 이용하여 404 에러 등 처리하기

3가지 파일만 수정 및 추가해주자

[1] application.yml

server:
  error:
    path: /errorPath

*기존에 있는 파일에 해당 프로퍼티만 추가해주면 됨

 

[2] MyErrorController.java 

package com.web.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

@Controller
public class MyErrorController implements ErrorController {
	@RequestMapping("/errorPath") 
	public ModelAndView handleError(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("error");

		int errorCode = (int) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
		if(errorCode == HttpStatus.BAD_REQUEST.value()){
			mav.addObject("errorMsg", HttpStatus.BAD_REQUEST.getReasonPhrase());
			mav.addObject("errorCode", HttpStatus.BAD_REQUEST.value());
		} else if(errorCode == HttpStatus.UNAUTHORIZED.value()){
			mav.addObject("errorMsg", HttpStatus.UNAUTHORIZED.getReasonPhrase());
			mav.addObject("errorCode", HttpStatus.UNAUTHORIZED.value());
		} else if(errorCode == HttpStatus.FORBIDDEN.value()){
			mav.addObject("errorMsg", HttpStatus.FORBIDDEN.getReasonPhrase());
			mav.addObject("errorCode", HttpStatus.FORBIDDEN.value());
		} else if(errorCode == HttpStatus.NOT_FOUND.value()){
			mav.addObject("errorMsg", HttpStatus.NOT_FOUND.getReasonPhrase());
			mav.addObject("errorCode", HttpStatus.NOT_FOUND.value());
		} else if(errorCode == HttpStatus.INTERNAL_SERVER_ERROR.value()){
			mav.addObject("errorMsg", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
			mav.addObject("errorCode", HttpStatus.INTERNAL_SERVER_ERROR.value());
		} else {
			mav.addObject("errorMsg", "Unknown Error");
			mav.addObject("errorCode", "?");
		}

		return mav;
	}
}

* 파일 경로는 상관 없음

 

[3] error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>제목</title>
</head>
<body>
[(${errorCode})] - [(${errorMsg})]
</body>
</html>

*파일 경로 /src/main/resources/templates/error.html

*재미있는 사실은 [1]과 [2]의 작업을 하지 않고 [3]의 작업만 해도 에러가 발생했을 경우, error.html 페이지를 불러온다. (Spring에서 디폴트로 error.html로 불러오는 것으로 추측되고, 만약 error.html 파일명을 변경하면 해당 페이지를 불러오지 않는다)

 

[실행화면]