코딩하는 문과생

[Spring] Spring 프레임워크(11) - 예외처리 본문

웹 프로그래밍/Spring

[Spring] Spring 프레임워크(11) - 예외처리

코딩하는 문과생 2020. 3. 12. 14:47

[개요]

서버에서 발생된 예외를 최종 사용자에게 전달되는 것을 방지

  • System예외는 Business예외로 다시 던지는 방식 사용
  • @ExceptionHandler@ControllerAdvice를 사용

 

[특징]

  • 컨트롤러 기반: 부가기능을 제공하는 Advice클래스를 작성. 즉, 컨트롤러에서 처리한다.
  • 글로벌 Exception 핸들러: @ControllerAdvice어노테이션을 포함한 클래스는 전역 예외처리 컨트롤러가 된다.
  • SQLException은 복구가 불가능, MyBatis에서 DataAccessException으로 re-throwing한다.

- @ControllerAdvice

  • 모든 클래스에 대응한다는 의미
  • 스프링 3.2이상 사용
  • @Controller나 @RestContrller에서 발생하는 예외를 Catch
  • servlet-context에서 include시킨다.

- @ExceptionHandler

처리할 예외를 지정

 

 

ex. 예외처리

- BizException 생성

package kr.co.acomp.hello.exception;

//사용자 정의 예외
public class BizException extends RuntimeException{

	public BizException() {
		super();
	}
	public BizException(Throwable t) {
		super(t);
	}
	public BizException(String msg) {
		super(msg);
	}
	
}

- GlobalExceptionHandler 생성

package kr.co.acomp.hello.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import kr.co.acomp.hello.exception.BizException;

@ControllerAdvice
//컨트롤러이면서 예외 처리가 가능
public class GlobalExceptionHandler {
	
	@ExceptionHandler(BizException.class)
	//파라미터로 예외 클래스를 넣어준다.
	public String handleBizException(Exception e, Model model) {
		model.addAttribute("type", e.getClass().getSimpleName());
		model.addAttribute("msg", e.getMessage());
		return "error";
	}
	
}

- BbsService 수정

	public void testService() {
		System.out.println("target invoked..");
		throw new BizException("testService fail..");
	}

- BbsController 수정

	@GetMapping("")
	public String index() {
		bbsService.testService();
		//예외가 여기로 넘어온다.->GlobalExceptionHandler가 호출
		return "index";
	}

-error.jsp 생성

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>에러 발생!</h1>
	<h2>error type: ${type}</h2>
	<h2>msg: ${msg}</h2>
</body>
</html>

error.jsp 파일에 에러 출력

ex. MyBatis 에러 추가

- ArticleDAO 에러 발생

public String handleBizException(Exception e, Model model) {
		model.addAttribute("type", e.getClass().getSimpleName());
		model.addAttribute("msg", e.getMessage());
		return "error";
	}

- BbsController 수정 - Article 바로 생성

	@GetMapping("")
	public String index() {
		bbsService.registArticle(new Article(5, "jj", "test", "testtest"));
		//예외가 여기로 넘어온다.->GlobalExceptionHandler가 호출
		return "index";
	}

- GlobalExceptionHandler추가

	@ExceptionHandler(MyBatisSystemException.class)
	public String handleMBSException(Exception e, Model model) {
		model.addAttribute("type", e.getClass().getSimpleName());
		model.addAttribute("msg", e.getMessage());
		return "error";
	}

error.jsp 파일에 에러 출력