public class RtopExceptionHandler implements HandlerExceptionResolver{
private static final Logger logger = LoggerFactory.getLogger(RtopExceptionHandler.class);
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o,
Exception ex) {
//处理buservice的异常
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
if(ex instanceof AccessException) {
if(BuserviceConstants.HANDLER_DIGEST_LOGGER.isInfoEnabled()) {
BuserviceConstants.HANDLER_DIGEST_LOGGER.info("The current request failed, the reason:" + ex);
}
AccessException e = (AccessException)ex;
String redirectUrl = e.getRedirectUrl();
String requestURI = request.getRequestURI();
if(StringUtils.endsWithIgnoreCase(requestURI, ".json")) {
try {
ErrorCodeEnum errorCode = e.getErrorCode();
String buserviceErrorCode = errorCode == null? ErrorCodeEnum.UNKNOW.name():errorCode.name();
String buserviceErrorMsg = errorCode == null? ErrorCodeEnum.UNKNOW.getDescCn():errorCode.getDescCn();
RtopHttpResult result = RtopHttpResult.Failure(buserviceErrorCode, buserviceErrorMsg);
if(ErrorCodeEnum.USER_NOT_LOGIN == errorCode){
//如果返回的错误是用户未登录,则将请求强制改为success,为了防止前端弹框展示错误信息.由前端直接跳转到登录页面.
result.setSuccess(true);
}
PrintWriter pw = response.getWriter();
String callback = request.getParameter("callback");
if(StringUtil.isNotBlank(callback)) {
pw.print(callback + "(" + JSON.toJSONString(result) + ")");
} else {
pw.print(JSON.toJSON(result));
}
pw.close();
} catch (Exception var13) {
BuserviceConstants.HANDLER_DIGEST_LOGGER.info("The current JSON request fails, intercepting failure:" + var13);
}
} else {
return StringUtil.isNotBlank(redirectUrl)?this.returnPage("redirect:" + redirectUrl, ex, new ModelAndView()):this.returnPage("/error", ex, new ModelAndView());
}
}else if(ex instanceof ErrorCodeException){
ErrorCodeException errorCodeException = (ErrorCodeException) ex;
LoggerUtil.error(errorCodeException, "");
String errorCode = errorCodeException.getErrorCode().getCode();
String errorMsg = errorCodeException.getErrorCode().getMessage();
RtopHttpResult result = RtopHttpResult.Failure(errorCode, errorMsg);
try{
PrintWriter pw = response.getWriter();
pw.print(JSON.toJSON(result));
pw.close();
}catch (Exception e) {
LoggerUtil.info(logger, "response in RtopExceptionHandler error" + e.getMessage());
}
}else if(ex instanceof RuntimeException){
if(ex instanceof IllegalStateException){
return null;
}
LoggerUtil.error(ex, "");
RtopHttpResult result = RtopHttpResult.Failure(RtopAppErrorCode.INTERNAL_ERROR);
try{
PrintWriter pw = response.getWriter();
pw.print(JSON.toJSON(result));
pw.close();
}catch (Exception e) {
LoggerUtil.info(logger, "response in RtopExceptionHandler error" + e.getMessage());
}
}
return null;
}
public ModelAndView returnPage(String page, Exception ex, ModelAndView view) {
view.addObject("exception", ex);
view.setViewName(page);
return view;
}
}