BasicErrorController
BasicErrorController는 기본 에러 핸들러이다.
내용을 보면 아래와 같이 html과 json 형식으로 응답을 하는 것을 알 수 있다.
우리가 흔히 볼 수 있는 아래와 같은 웹서비스의 404 에러 페이지도 이 핸들러가 처리하는 것이다.

요청의 헤더에 'test/html' 정보가 담겨 있기 때문에 응답을 html 형식으로 하게 된다.
만약 curl을 이용해 아래와 같이 요청한다면 json 형태의 에러 응답을 하게 될 것이다.
curl http://127.0.0.1:8080/aa
<BasicErrorController.java>
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
return new ResponseEntity<>(body, status);
public static final String TEXT_HTML_VALUE = "text/html";
Exception 핸들러 생성
Exception을 처리하는 핸들러를 만들어 보자.
<SampleController.java>
@Controller
public class SampleController {
@GetMapping("/test1")
public String test() {
throw new SampleException();
}
@ExceptionHandler(SampleException.class)
@ResponseBody
public AppError responseError(SampleException e) {
AppError appError = new AppError();
appError.setMessage("error.app.key");
appError.setReson("IDK IDK IDK");
return appError;
}
}
<AppError.java>
@Getter(AccessLevel.PUBLIC)
@Setter(AccessLevel.PUBLIC)
public class AppError {
public String message;
public String reson;
}
<SampleException.java>
public class SampleException extends RuntimeException {
}

커스텀 에러 페이지
에러가 났을 때 http status 코드에 따라 다른 페이지를 보여줄 수 있다.
에러 페이지를 resource 경로에서 생성해 보자.
커스텀 에러 페이지는 */error의 하위 경로에 있어야 한다.
파일 이름을 5xx, 4xx와 같이 지정할 경우 각각 500, 400번대의 에러를 처리한다.
만약 404.html과 같이 특정 상태를 지정하면 해당 파일을 보여주게 된다.


<404.html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
404 페이지 찾을수 없음!!
</body>
</html>
링크
해당 포스팅은 백기선 님의 인프런 강의를 보고 작성하였습니다.
반응형
'Java & 스프링 > 스프링부트 톺아보기' 카테고리의 다른 글
| [Spring Boot] 스프링 부트의 index 페이지, 파비콘 (0) | 2019.12.02 |
|---|---|
| [Spring Boot] 스프링부트의 웹 jar (0) | 2019.12.02 |
| [스프링 부트] war 파일과 외부 톰캣을 이용한 서버 배포 (0) | 2019.10.30 |
| [스프링 부트] 정적 리소스 - static resource (0) | 2019.10.24 |
| [스프링 부트] 스프링 MVC - 스프링 부트의 Message Converter (0) | 2019.10.23 |
댓글