springmvc 处理异常 springmvc
程序员文章站
2022-03-22 14:10:31
...
springmvc controller层的异常:
@RequestMapping("/test")
public String exception() {
int i = 0;
i=i/1;
return "";
}
(1)页面访问http://localhost:8080/boot/user/test
Whitelabel Error Page
显示默认的异常页面
(2)使用@ControllerAdvice自定义异常统一处理页面
页面访问http://localhost:8080/boot/user/
{"message":"Could not open JDBC Connection for transaction;
nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure\n\nThe last packet sent successfully to the server
was 0 milliseconds ago. The driver has not received any packets from the server.",
"url":"http://localhost:8080/boot/user/"}
页面被GlobalExceptonHandler处理
(3)异常处理类
@ControllerAdvice
public class GlobalExceptonHandler {
@ExceptionHandler(value=Exception.class)
@ResponseBody
public Object handle(HttpServletRequest req, Exception e) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
map.put("message", e.getMessage());
map.put("url", req.getRequestURL().toString());
return map;
}
//另一种方法跳转到异常页面
@ExceptionHandler(value=Exception.class)
public ModelAndView handle(HttpServletRequest req, Exception e) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
map.put("message", e.getMessage());
map.put("url", req.getRequestURL().toString());
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
mv.addObject("map", map);
return mv;
}
}
android入门实例:https://gitbook.cn/gitchat/activity/5d382e64b669c0566c335b32
@RequestMapping("/test")
public String exception() {
int i = 0;
i=i/1;
return "";
}
(1)页面访问http://localhost:8080/boot/user/test
Whitelabel Error Page
显示默认的异常页面
(2)使用@ControllerAdvice自定义异常统一处理页面
页面访问http://localhost:8080/boot/user/
{"message":"Could not open JDBC Connection for transaction;
nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure\n\nThe last packet sent successfully to the server
was 0 milliseconds ago. The driver has not received any packets from the server.",
"url":"http://localhost:8080/boot/user/"}
页面被GlobalExceptonHandler处理
(3)异常处理类
@ControllerAdvice
public class GlobalExceptonHandler {
@ExceptionHandler(value=Exception.class)
@ResponseBody
public Object handle(HttpServletRequest req, Exception e) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
map.put("message", e.getMessage());
map.put("url", req.getRequestURL().toString());
return map;
}
//另一种方法跳转到异常页面
@ExceptionHandler(value=Exception.class)
public ModelAndView handle(HttpServletRequest req, Exception e) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
map.put("message", e.getMessage());
map.put("url", req.getRequestURL().toString());
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
mv.addObject("map", map);
return mv;
}
}
android入门实例:https://gitbook.cn/gitchat/activity/5d382e64b669c0566c335b32
上一篇: springmvc源码解析