Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Spring4 Web MVC
Controller Exception Handling
@ExceptionHandler, @ControllerAdvice
이종철, 탑크리에듀(topcredu.co.kr)
컨트롤러 기반 예외처리
 컨트롤러 내부 메소드 위에 @ExceptionHandler를 사용하면 된다.
스프링은 컨트롤러 안에 @ExceptionHandler를 사용한 메소드가
존재하면 그 메소드가 컨트롤러 내부의 예외...
컨트롤러 기반 예외처리(예문)
@Controller
public class EmpController {
@RequestMapping(value="/emp/{empno}", method=RequestMethod.GET)
...
글로벌 예외처리
 @ExceptionHandler : 스프링 컨트롤러에서 정의한 메소드에서
기술한 예외가 발생되면 자동으로 받아낼 수 있는데 이를 이용하여
컨트롤러에서 발생하는 예외를 View단 JSP등으로 보내서 처...
글로벌 예외처리 예문(Controller)
@Controller
public class HomeController {
@RequestMapping(value = "/")
public String hello() throw...
글로벌 예외처리 예문
(ExceptionControllerAdvice.java)
@ControllerAdvice //모든 컨트롤러에 대응된다.
public class ExceptionControllerAdvice {
@...
글로벌 예외처리 예문(home.jsp)
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body>
<h1>Spring MVC Exception H...
글로벌 예외처리 예문(exception.jsp)
<html>
<head>
<title>Spring MVC Exception example</title>
</head>
<body>
<h1>Error Handing Page...
실행 결과
http://localhost:8080/springmvcexception/
Spring4 @RestController 컨트롤러 기반 예외처리 - 1
@RestController @RequestMapping("/emp")
public class EmpController {
@ExceptionHa...
public class EmpNotFoundException extends RuntimeException {
public EmpNotFoundException(String empno){
super(empno +" not...
@RestController
@RequestMapping("/emp")
class EmpApiController {
@RequestMapping(value = "{empno}", produces = "applicatio...
@ControllerAdvice(annotations = RestController.class)
class ExceptionHandlerAdvice {
@ExceptionHandler(value = EmpNotFound...
This practice makes the Expert!
스프링,마이바티스기초
단기속성과정
자바기초에서JSP스프링,
MyBatis까지
Spring Framework & JPA
Upcoming SlideShare
Loading in …5
×

스프링컨트롤러예외처리,@ExceptionHandler, @ControllerAdvice

12,579 views

Published on

스프링 WEB MVC에서 컨트롤러에서 예외처리하는 방법에 관해 설명한 PPT 입니다.
@ExceptionHandler는 스프링 컨트롤러에서 정의한 메소드에서 기술한 예외가 발생되면 자동으로 받아낼 수 있는데 이를 이용하여 컨트롤러에서 발생하는 예외를 View단 JSP등으로 보내서 처리할 수 있으며@ControllerAdvice는 스프링3.2 이상에서 사용가능하며 @Controller 나 스프링 4.0이상에서 지원하는 @RestController 에서 발생하는 예외 등을 catch하는 기능을 가지고 있으며 클래스 위에 @ControllerAdvice를 붙이고 어떤 예외를 잡아낼 것인지 메소드 상단에 @ExceptionHandler(예외클래스명.class)를 기술합니다. 스프링4.0이상에서는 특정한 컨트롤러만 지정해서 캐치할 수 있죠

Published in: Software
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (Unlimited) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download Full EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ACCESS WEBSITE for All Ebooks ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download doc Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ..................................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookeBOOK Crime, eeBOOK Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (Unlimited) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download Full EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ACCESS WEBSITE for All Ebooks ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download doc Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ..................................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookeBOOK Crime, eeBOOK Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (Unlimited) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download Full EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ACCESS WEBSITE for All Ebooks ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download doc Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ..................................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookeBOOK Crime, eeBOOK Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • If you just broke up with your Ex,you have to follow these steps to get her back or risk ruining your chances. Click here ◆◆◆ http://goo.gl/FXTq7P
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

스프링컨트롤러예외처리,@ExceptionHandler, @ControllerAdvice

  1. 1. Spring4 Web MVC Controller Exception Handling @ExceptionHandler, @ControllerAdvice 이종철, 탑크리에듀(topcredu.co.kr)
  2. 2. 컨트롤러 기반 예외처리  컨트롤러 내부 메소드 위에 @ExceptionHandler를 사용하면 된다. 스프링은 컨트롤러 안에 @ExceptionHandler를 사용한 메소드가 존재하면 그 메소드가 컨트롤러 내부의 예외를 처리하도록 한다.  @ExceptionHandler의 인자로 들어오는 예외가 발생하는 경우에 해당 메소드가 실행된다.
  3. 3. 컨트롤러 기반 예외처리(예문) @Controller public class EmpController { @RequestMapping(value="/emp/{empno}", method=RequestMethod.GET) public String getEmp(@PathVariable("empno") int empno, Model model) { if(empno==null) throw new EmpNotFoundException(id); else { ...... } } @ExceptionHandler(EmpNotFoundException.class) //EmpNotFoundException에 대한 예외처리 메소드 public ModelAndView exHandler(HttpServletRequest request, Exception ex){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("exception", ex); modelAndView.addObject("url", request.getRequestURL()); modelAndView.setViewName("error"); return modelAndView; } }
  4. 4. 글로벌 예외처리  @ExceptionHandler : 스프링 컨트롤러에서 정의한 메소드에서 기술한 예외가 발생되면 자동으로 받아낼 수 있는데 이를 이용하여 컨트롤러에서 발생하는 예외를 View단 JSP등으로 보내서 처리할 수 있다.  @ControllerAdvice : @ControllerAdvice는 스프링3.2 이상에서 사용가능하며 @Controller 나 스프링 4.0이상에서 지원하는 @RestController 에서 발생하는 예외 등을 catch하는 기능을 가지 고 있다. 클래스 위에 @ControllerAdvice를 붙이고 어떤 예외를 잡 아낼 것인지 메소드 상단에 @ExceptionHandler(예외클래스 명.class)를 기술한다. 스프링4.0이상에서는 특정한 컨트롤러만 지정 해서 캐치할 수 있다.
  5. 5. 글로벌 예외처리 예문(Controller) @Controller public class HomeController { @RequestMapping(value = "/") public String hello() throws IOException { // 뷰이름 이름, hello.jsp 호출 return "home"; } @RequestMapping(value = "/test") public String test() throws IOException { throw new IOException("occured IOException..."); } }
  6. 6. 글로벌 예외처리 예문 (ExceptionControllerAdvice.java) @ControllerAdvice //모든 컨트롤러에 대응된다. public class ExceptionControllerAdvice { @ExceptionHandler(Exception.class) //모든 예외를 받음 public ModelAndView exception(Exception e) { ModelAndView mav = new ModelAndView("exception"); mav.addObject("name", e.getClass().getSimpleName()); mav.addObject("message", e.getMessage()); return mav; } }
  7. 7. 글로벌 예외처리 예문(home.jsp) <html> <head> <title>Spring MVC Exception Handling</title> </head> <body> <h1>Spring MVC Exception Handling</h1> <a href="/springmvcexception/test">Click here to test Exception handling</a> </body> </html>
  8. 8. 글로벌 예외처리 예문(exception.jsp) <html> <head> <title>Spring MVC Exception example</title> </head> <body> <h1>Error Handing Page</h1> <b>${name}</b>: ${message} </body> </html>
  9. 9. 실행 결과 http://localhost:8080/springmvcexception/
  10. 10. Spring4 @RestController 컨트롤러 기반 예외처리 - 1 @RestController @RequestMapping("/emp") public class EmpController { @ExceptionHandler(EmpNotFoundException.class) //EmpNotFoundException 예외처리용 public ErrorDetail myError(HttpServletRequest request, Exception exception) { ErrorDetail error = new ErrorDetail(); error.setStatus(HttpStatus.BAD_REQUEST.value()); error.setMessage(exception.getLocalizedMessage()); error.setUrl(request.getRequestURL().append("/emperror/").toString()); return error; } @RequestMapping("/get") public Emp getEmp(@RequestParam(value="empno") String empno) { if (empno == null) throw new EmpNotFoundException(empno); ...... return emp; } }
  11. 11. public class EmpNotFoundException extends RuntimeException { public EmpNotFoundException(String empno){ super(empno +" not found!"); } } http://localhost:8080/emp/get?empno=9999 존재하지 않는 사원이라면 오류는 JSON 형태로 리턴된다. {"status":400,"message":"9999 not found!","url":"http://localhost:8080/emp/get/emperror/"} Spring4 @RestController 컨트롤러 기반 예외처리 - 2
  12. 12. @RestController @RequestMapping("/emp") class EmpApiController { @RequestMapping(value = "{empno}", produces = "application/json") @ResponseStatus(value = HttpStatus.OK) Emp getEmp(@PathVariable Long empno) { if (empno == null) throw new EmpNotFoundException(empno); } } Spring4 @RestController 글로벌 예외처리 - 1
  13. 13. @ControllerAdvice(annotations = RestController.class) class ExceptionHandlerAdvice { @ExceptionHandler(value = EmpNotFoundException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public ErrorDetail myError(HttpServletRequest request, Exception exception) { ErrorDetail error = new ErrorDetail(); error.setStatus(HttpStatus.BAD_REQUEST.value()); error.setMessage(exception.getLocalizedMessage()); error.setUrl(request.getRequestURL().append("/emperror/").toString()); return error; } } Spring4 @RestController 글로벌 예외처리 - 2
  14. 14. This practice makes the Expert! 스프링,마이바티스기초 단기속성과정 자바기초에서JSP스프링, MyBatis까지 Spring Framework & JPA

×