1.描述:
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。
那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring MVC统一处理异常的解决和实现过程。
注入spring容器中
<bean id="webExceptionResolver"class="com.sgcc.fsp.manage.web.controller.WebExceptionResolver" />
相当于一个异常处理拦截器,定位在控制层后__触发点:控制层抛出异常后触发此方法__
1、对ResponseBody 请求可直接将异常抛出到 response 控制台中
2、对于普通请求可将异常信息存入隐藏域
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 统一异常处理(Controller切面方式实现)
* <p>
* 1、@ControllerAdvice:扫描所有Controller;
* 2、@ControllerAdvice(annotations=RestController.class):扫描指定注解类型的Controller;
* 3、@ControllerAdvice(basePackages={"com.aaa","com.bbb"}):扫描指定package下的Controller
*
* @author
*/
//@ControllerAdvice
//@Component
public class WebExceptionResolver implements HandlerExceptionResolver {
private static transient Logger logger = LoggerFactory.getLogger(WebExceptionResolver.class);
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
logger.error("WebExceptionResolver:{}", ex);
// if json
boolean isJson = false;
HandlerMethod method = (HandlerMethod) handler;
ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
if (responseBody != null) {
isJson = true;
}
// error result 判断是否有异常
ReturnT<String> errorResult = null;
if (ex instanceof XxlSsoException) {
errorResult = new ReturnT<String>(ReturnT.FAIL_CODE, ex.getMessage());
} else {
errorResult = new ReturnT<String>(ReturnT.FAIL_CODE, ex.toString().replaceAll("\n", "<br/>"));
}
// response
ModelAndView mv = new ModelAndView();
if (isJson) {
try {
response.setContentType("application/json;charset=utf-8");
response.getWriter().print("");
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return mv;
} else {
mv.addObject("exceptionMsg", errorResult.getMsg());
mv.setViewName("/common/common.exception");
return mv;
}
}
}