예외처리

Jimin·2022년 11월 6일
0

스프링 - fastcampus

목록 보기
13/21

@ExceptionHandler와 @ControlleAdvice

@ExceptionHandler

예외 처리를 위한 메서드를 작성하고 @ExceptionHandler를 붙인다.

@ExceptionHandler(처리할 예외)
public String catcher(처리할 예외, Model m) { // 예외 처리 메서드, try-catch 역할을 한다.
	m.addAttribute("ex", ex);
	return "error";
}
package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExceptionController {
	
	@ExceptionHandler(Exception.class)
	public String catcher(Exception ex, Model m) {
		m.addAttribute("ex", ex);
		return "error";
	}
	
	@ExceptionHandler(NullPointerException.class)
	public String catcher2(NullPointerException ex, Model m) {
		m.addAttribute("ex", ex);
		return "error";
	}
	
	@RequestMapping("/ex")
	public String main() throws Exception{
		throw new Exception("예외가 발생했습니다.");
	}
	
	@RequestMapping("/ex2")
	public String main2() throws Exception{
		throw new NullPointerException("예외가 발생했습니다.");
	}
}

@ControlleAdvice

@ControlleAdvice로 전역 예외 처리 클래스 작성 가능(패키지 지정 가능)

예외 처리 메서드가 중복된 경우, 컨트롤러 내의 예외 처리 메서드가 우선된다.


@ResponseStatus

응답 메시지의 상태 코드를 변경할 때 사용

  1. 예외 처리 메서드
  2. 사용자정의 예외 클래스

ExceptionResolver

  1. 클라이언트의 요청: /ch2/ex
  2. DispatcherServlet
  3. Controller가 예외를 받음
  4. Controller가 예외를 다시 DispatcherServlet으로 전달
  5. DispatcherServlet에서 에러를 처리할 수 있는 예외처리기본전략(Resolver)들을 확인한다.

스프링에서의 예외 처리

  1. 컨트롤러 메서드 내에서 try-catch로 처리
  2. 컨트롤러에 @ExceptionHandler메서드가 처리
  3. @ControllerAdvice클래스의 @ExcpetionHandler 메서드가 처리
  4. 예외 종류별로 뷰 지정 - SimpleMappingExceptionResolver
  5. 응답 상태 코드별로 뷰 지정 -
profile
https://github.com/Dingadung

0개의 댓글

관련 채용 정보