@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ExceptionHandler({Exception.class})
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.error("服务器发生异常:"+e.getMessage());
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
logger.error(stackTraceElement.toString());
}
//判断是普通请求还是异步请求
//以下代码可以当作固定格式
String xRequestedWith = request.getHeader("x-requested-with");
if("XMLHttpRequest".equals(xRequestedWith)){
response.setContentType("application/plain;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write(CommunityUtil.getJSONString(1,"服务器异常!"));
}else{
response.sendRedirect(request.getContextPath()+"/error");
}
}
代码示例如上。