下面列出了org.springframework.web.servlet.view.json.MappingJackson2JsonView#setAttributesMap ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object o, Exception e) {
LOGGER.error("rest error:", e);
ModelAndView modelAndView = new ModelAndView();
try {
ResultInfo resultInfo = new ResultInfo().setStatus(ResultStatus.ERROR.getCode())
.setMsg(ResultInfo.MSG_ERROR);
Map<String, Object> attr = JSON.parseObject(JSON.toJSONString(resultInfo), Map.class);
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setAttributesMap(attr);
modelAndView.setView(view);
} catch (Exception e1) {
e1.printStackTrace();
}
return modelAndView;
}
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ModelAndView mv = new ModelAndView();
MappingJackson2JsonView view = new MappingJackson2JsonView();
Map<String, Object> attributes = new HashMap();
if (ex instanceof MaxUploadSizeExceededException) {
attributes.put("code", ResultCode.C403.code);
attributes.put("msg", "Maximum upload size of " + ((MaxUploadSizeExceededException) ex).getMaxUploadSize() + " bytes exceeded");
logger.warn(ex.getMessage());
} else {
attributes.put("code", ResultCode.C500.code);
attributes.put("msg", ResultCode.C500.desc);
logger.error("Internal server error", ex);
}
view.setAttributesMap(attributes);
mv.setView(view);
return mv;
}
/**
* 获取其它异常。包括500
*
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request,
HttpServletResponse response,
Exception e, Model model) throws IOException {
e.printStackTrace();
if (isAjax(request)) {
ModelAndView mav = new ModelAndView();
MappingJackson2JsonView view = new MappingJackson2JsonView();
Map<String, Object> attributes = new HashMap<String, Object>();
if (e instanceof UnauthorizedException) {
attributes.put("msg", "没有权限");
} else {
attributes.put("msg", e.getMessage());
}
attributes.put("code", "0");
view.setAttributesMap(attributes);
mav.setView(view);
return mav;
}
if (e instanceof UnauthorizedException) {
//请登录
log.error("无权访问", e);
return new ModelAndView("common/error/403");
}
//其他异常
String message = e.getMessage();
model.addAttribute("code", 500);
model.addAttribute("message", message);
return new ModelAndView("common/error/500");
}