ajax的异常要返回的是一串信息而不是视图,所以@ControllerAdvice 要换为@RestControllerAdvice
普通的访问webservice 可以用
@ControllerAdvice
和@ExceptionHandler(Exception.class) 去捕获全局异常
@ControllerAdvice
public class MyException {
@ExceptionHandler(Exception.class)
public Object errorHander(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Exception e) throws Exception {
e.printStackTrace();
ModelAndView m = new ModelAndView();
m.addObject("error", e);
m.addObject("url", httpServletRequest.getRequestURL());
m.setViewName("error");
return m;
}
}
但是ajax的异常并不能返回视图,而是返回字符串或者json格式的数据,我们捕获完异常可以把异常信息包装起来,加上状态码和其他数据
ajax请求页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<script type="text/javascript" src="/js/jquery-1.11.0.js"></script>
</head>
<body>
<script type="text/javascript">
$.