SpringMVC-异常处理
2020-06-14 本文已影响0人
张明学
SpringMVC的异常处理是指统一包装异常的展示信息,实现HandlerExceptionResolver接口即可。
开发统一处理的异常解析器
public class GlobalExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,
Object o,
Exception e) {
if (o instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) o;
log.error("异常#Controller={},Method={}", handlerMethod.getBean(), handlerMethod.getMethod().getName(), e);
// todo 判断属于Ajax的请求还是普通的页面请求
if (isAsyncRequest(request, handlerMethod)) {
// 返回JSON格式数据
return buildJsonResponse(request, response, handlerMethod, e);
} else {
// 返回重定向页面
return buildViewResponse(request, response, handlerMethod, e);
}
}
return null;
}
/**
* 构建JSON数据
*
* @return
*/
private ModelAndView buildJsonResponse(HttpServletRequest request,
HttpServletResponse response,
HandlerMethod handlerMethod,
Exception ex) {
BaseResponse baseResponse = new BaseResponse().setCode("10").setMessage(ex.getMessage());
// 使用jackson,也可以换成fastjson
ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
modelAndView.addObject("result", baseResponse);
return modelAndView;
}
/**
* 重定向错误页面
*
* @return
*/
private ModelAndView buildViewResponse(HttpServletRequest request,
HttpServletResponse response,
HandlerMethod handlerMethod,
Exception ex) {
ModelAndView errorView = new ModelAndView();
errorView.setViewName("redirect:/error-page");
errorView.addObject("errorMessage", ex.getMessage());
return errorView;
}
/**
* 根据handlerMethod的注解来判断是不是ajax请求
*/
public static boolean isAsyncRequest(HttpServletRequest request, HandlerMethod handlerMethod) {
// 方法上有@ResponseBody 表示返回JSON
ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
if (null != responseBody) {
return true;
}
//判断Controller类上有没有@RestController
RestController restController = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), RestController.class);
if (null != restController) {
return true;
}
//判断Controller类上有没有@ResponseBody
responseBody = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), ResponseBody.class);
if (null != responseBody) {
return true;
}
return false;
}
}
配置异常解析器
<bean id="globalExceptionResolver" class="com.zmx.GlobalExceptionResolver"/>