1.首先自定义异常类实现SimpleMappingExceptionResolver接口
public class PlatformMappingExceptionResolver extends
SimpleMappingExceptionResolver {
static Logger logger = LoggerFactory.getLogger(PlatformMappingExceptionResolver.class);
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
String viewName = determineViewName(ex, request);
// vm方式返回
if (viewName != null) {
if (!( request.getHeader("accept").indexOf("application/json") > -1 || ( request
.getHeader("X-Requested-With") != null && request
.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1 ) )) {
// 非异步方式返回
Integer statusCode = determineStatusCode(request, viewName);
if (statusCode != null) {
applyStatusCodeIfPossible(request, response, statusCode);
}
// 跳转到提示页面
ModelAndView view = new ModelAndView();
view.setViewName(viewName);
view.addObject("basePath", GlobalConfigHolder.getProperty("basePath"));
view.addObject("exception",ex);
return view;
} else {
// 异步方式返回
try {
PrintWriter writer = response.getWriter();
writer.write(ExceptionI18Message.getLocaleMessage(ex.getMessage()));
response.setStatus(404, ExceptionI18Message.getLocaleMessage(ex.getMessage()));
logger.error(getTrace(ex));
writer.flush();
} catch ( Exception e ) {
e.printStackTrace();
}
// 不进行页面跳转
return null;
}
} else {
return null;
}
}
public static String getTrace(Throwable t) {
StringWriter stringWriter= new StringWriter();
PrintWriter writer= new PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer buffer= stringWriter.getBuffer();
return buffer.toString();
}
}
public class BusinessException extends Exception {
private static final long serialVersionUID = 1L;
public BusinessException() {
}
public BusinessException(String message) {
super(message);
}
public BusinessException(Throwable cause) {
super(cause);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
}
参考资料:
http://blog.csdn.net/lcore/article/details/42126299
http://gaojiewyh.iteye.com/blog/1297746
2.在springmvc的dispatcherServlet.xml中进行如下配置
class="com.cisdi.ecis.common.exception.PlatformMappingExceptionResolver">