捕获全局异常
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class MyExceptionHandler {
public static final String ERROR_VIEW = "403";
@ExceptionHandler(value = Exception.class)
public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
e.printStackTrace();
if (isAjax(request)) {
Map<String, Object> result = new HashMap<>();
result = new HashMap<>();
result.put("error", "403");
result.put("title", e.getMessage());
return result;
} else {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName(ERROR_VIEW);
return mav;
}
}
public static boolean isAjax(HttpServletRequest httpRequest) {
String xRequestedWith = httpRequest.getHeader("X-Requested-With");
return (xRequestedWith != null && "XMLHttpRequest".equals(xRequestedWith));
}
}