原文地址:https://www.cnblogs.com/UncleWang001/p/10949318.htmlhtml
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; } }
@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); }
spring boot 默认状况下会映射到 /error 进行异常处理,可是提示并不十分友好,下面自定义异常处理,提供友好展现。java
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 }
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; } }
@RequestMapping("/home") public String home() throws Exception { // throw new Exception("Sam 错误"); throw new MyException("101", "Sam 错误"); }
{"msg":"Sam 错误","code":"101"}
@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; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>错误页面</title> </head> <body> <h1>${code}</h1> <h1>${msg}</h1> </body> </html>