springmvc 处理异常

白诗秀儿 关注

收藏于 : 2018-12-16 19:46   被转藏 : 1   


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;
}
}

0
0
分享到:
评论
 阅读文章全部内容  
点击查看
文章点评
相关文章
白诗秀儿 关注

文章收藏:1308

TA的最新收藏