Original: the Spring the Boot Series (eight) @ControllerAdvice intercept abnormal and unified treatment
In the spring 3.2, add the @ControllerAdvice annotations can be used to define @ ExceptionHandler, @ InitBinder, @ ModelAttribute , and apply to all @RequestMapping in. Reference: @ControllerAdvice document
I. INTRODUCTION
Creating MyControllerAdvice, and add @ControllerAdvice comment.
package com.sam.demo.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap; import java.util.Map; /** * controller 增强器 * @author sam * @since 2017/7/17 */ @ControllerAdvice public class MyControllerAdvice { /** * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器 * @param binder */ @InitBinder public void initBinder(WebDataBinder binder) {} /** * 把值绑定到Model中,使全局@RequestMapping可以获取到该值 * @param model */ @ModelAttribute public void addAttributes(Model model) { model.addAttribute("author", "Magical Sam"); } /** * 全局异常捕捉处理 * @param ex * @return */ @ResponseBody @ExceptionHandler(value = Exception.class) public Map errorHandler(Exception ex) { Map map = new HashMap(); map.put("code", 100); map.put("msg", ex.getMessage()); return map; } }
After starting the application, is @ ExceptionHandler, @ InitBinder, @ ModelAttribute annotated method will be applied to the method @RequestMapping annotations.
@ModelAttribute: the value set in the Model, for all the methods are annotated in @RequestMapping, can be obtained through a ModelMap, as follows:
@RequestMapping("/home")
public String home(ModelMap modelMap) {
System.out.println(modelMap.get("author")); } //或者 通过@ModelAttribute获取 @RequestMapping("/home") public String home(@ModelAttribute("author") String author) { System.out.println(author); }
@ExceptionHandler intercepted an exception, we can custom exception handling is achieved by the comment. Which, @ ExceptionHandler configuration value specified exception types need to intercept the above intercepted Exception.class this anomaly.
Second, custom exception handling (global exception handler)
spring boot by default mapped to / error exception handling, but that it is not very friendly, following the custom exception handling, a friendly show.
1. Writing custom exception class:
package com.sam.demo.custom;
/**
* @author sam
* @since 2017/7/17
*/
public class MyException extends RuntimeException { public MyException(String code, String msg) { this.code = code; this.msg = msg; } private String code; private String msg; // getter & setter }
Note: spring for transaction rollback for a RuntimeException will.
2, the preparation of global exception handler class
Creating MyControllerAdvice.java, as follows:
package com.sam.demo.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map; /** * controller 增强器 * * @author sam * @since 2017/7/17 */ @ControllerAdvice public class MyControllerAdvice { /** * 全局异常捕捉处理 * @param ex * @return */ @ResponseBody @ExceptionHandler(value = Exception.class) public Map errorHandler(Exception ex) { Map map = new HashMap(); map.put("code", 100); map.put("msg", ex.getMessage()); return map; } /** * 拦截捕捉自定义异常 MyException.class * @param ex * @return */ @ResponseBody @ExceptionHandler(value = MyException.class) public Map myErrorHandler(MyException ex) { Map map = new HashMap(); map.put("code", ex.getCode()); map.put("msg", ex.getMsg()); return map; } }
3, controller thrown in for testing.
@RequestMapping("/home")
public String home() throws Exception { // throw new Exception("Sam 错误"); throw new MyException("101", "Sam 错误"); }
Start the application, visit: http: // localhost: 8080 / home, normal following json content, proof custom exception has been successfully intercepted.
{"msg":"Sam 错误","code":"101"}
* If you do not return json data, and to render a page template is returned to the browser, so you can achieve MyControllerAdvice:
@ExceptionHandler(value = MyException.class)
public ModelAndView myErrorHandler(MyException ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error"); modelAndView.addObject("code", ex.getCode()); modelAndView.addObject("msg", ex.getMsg()); return modelAndView; }
In the templates directory, add error.ftl (used here freemarker) rendering:
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>错误页面</title> </head> <body> <h1>${code}</h1> <h1>${msg}</h1> </body> </html>