转载: http://blog.csdn.net/m13321169565/article/details/7641978
废话不多,直接说重点。
一 创建异常拦截类
(这里将 webapi 和 web异常放在一起处理。但是文件夹是两个的。关于 LogHelper.WebLog和LogHelper.ApiLog)
参见文章:http://blog.csdn.net/hanjun0612/article/details/72639867
public class AnnotationHandlerMethodExceptionResolver extends ExceptionHandlerExceptionResolver {
private String defaultErrorView;
public String getDefaultErrorView() {
return defaultErrorView;
}
public void setDefaultErrorView(String defaultErrorView) {
this.defaultErrorView = defaultErrorView;
}
/***
* 异常后跳转到页面
*/
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
try {
if (handlerMethod == null) {
return null;
}
Method method = handlerMethod.getMethod();
if (method == null) {
return null;
}
ModelAndView returnValue = super.doResolveHandlerMethodException(request, response, handlerMethod, exception);
ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(method, ResponseBody.class);
if (responseBodyAnn != null) {
ResponseStatus responseStatusAnn = AnnotationUtils.findAnnotation(method, ResponseStatus.class);
if (responseStatusAnn != null) {
HttpStatus responseStatus = responseStatusAnn.value();
String reason = responseStatusAnn.reason();
if (!StringUtils.hasText(reason)) {
response.setStatus(responseStatus.value());
} else {
response.sendError(responseStatus.value(), reason);
}
}
return handleResponseBody(returnValue, request, response);
}
if (returnValue.getViewName() == null) {
returnValue.setViewName(defaultErrorView);
}
return returnValue;
} catch (Exception e) {
LogerHelper.WebLog(e.getMessage());
return null;
}
}
/**
* 异常后 返回json
*
* @param returnValue
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private ModelAndView handleResponseBody(ModelAndView returnValue, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Map value = returnValue.getModelMap();
HttpInputMessage inputMessage = new ServletServerHttpRequest(request);
List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
if (acceptedMediaTypes.isEmpty()) {
acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
}
MediaType.sortByQualityValue(acceptedMediaTypes);
HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
Class<?> returnValueType = value.getClass();
List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
if (messageConverters != null) {
for (MediaType acceptedMediaType : acceptedMediaTypes) {
for (HttpMessageConverter messageConverter : messageConverters) {
if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
messageConverter.write(value, acceptedMediaType, outputMessage);
return new ModelAndView();
}
}
}
}
if (logger.isWarnEnabled()) {
logger.warn("Could not find HttpMessageConverter that supports return type [" + returnValueType + "] and " + acceptedMediaTypes);
}
return null;
} catch (Exception e) {
LogerHelper.ApiLog(e.getMessage());
return null;
}
}
}
二 添加xml配置
找到springmvc-servlet.xml
添加:
<bean id="handlerExceptionResolver" class="com.sanju.sanjuSCM.ExceptionResolver.AnnotationHandlerMethodExceptionResolver">
<property name="defaultErrorView" value="error/500.jsp"/> <!--错误页面-->
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<!-- JSON转换器无需设置mediaType,由外部客户端调用时,手动设置相关mediaType -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
就完成了!
====================================================================================
下面是我项目中用到的。
配置文件和上面的还是一样
public class AnnotationHandlerMethodExceptionResolver extends ExceptionHandlerExceptionResolver {
private String defaultErrorView;
public String getDefaultErrorView() {
return defaultErrorView;
}
public void setDefaultErrorView(String defaultErrorView) {
this.defaultErrorView = defaultErrorView;
}
/***
* 异常后跳转到页面
*/
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
Method method=null;
ModelAndView returnValue=null;
try {
if (handlerMethod == null) {
return null;
}
method = handlerMethod.getMethod();
if (method == null) {
return null;
}
returnValue = super.doResolveHandlerMethodException(request, response, handlerMethod, exception);
//这里获取 @RestController和普通 @ResponseBody 的两种注解情况
Annotation restControllerAnn = method.getDeclaringClass().getAnnotation(RestController.class);
Annotation responseBodyAnn = restControllerAnn==null
?AnnotationUtils.findAnnotation(method, ResponseBody.class)
:restControllerAnn;
if (responseBodyAnn != null) {
ResponseStatus responseStatusAnn = AnnotationUtils.findAnnotation(method, ResponseStatus.class);
if (responseStatusAnn != null) {
HttpStatus responseStatus = responseStatusAnn.value();
String reason = responseStatusAnn.reason();
if (!StringUtils.hasText(reason)) {
response.setStatus(responseStatus.value());
} else {
response.sendError(responseStatus.value(), reason);
}
}
return handleResponseBody(returnValue, request, response,handlerMethod,exception);
}
if (returnValue.getViewName() == null) {
returnValue.setViewName(defaultErrorView);
}
return returnValue;
} catch (Exception e) {
SimpleDateFormat formatter =new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); ;
String exMsg="\r\n\r\n============================================================\r\n";
exMsg+="Date : "+(formatter.format(new Date()))+"\r\n\n";
exMsg+="ErrorMsg : "+exception+"\r\n\n";
exMsg+="ClassName : "+handlerMethod.getBean().getClass()+"\r\n\n";
exMsg+="MethodName : "+handlerMethod.getMethod().getName()+"\r\n\n";
exMsg+="Exception : "+handlerMethod +"\r\n\n";
LogerHelper.WebLog(exMsg);
return null;
}
}
/**
* 异常后 返回json
*
* @param returnValue
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private ModelAndView handleResponseBody(ModelAndView returnValue, HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) throws Exception {
ResultModel rm=new ResultModel();
rm.setMessage(exception.getMessage());
try {
String json= JsonConvert.toJSON(rm);
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
return null;
} catch (Exception e) {
SimpleDateFormat formatter =new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); ;
String exMsg="\r\n\r\n============================================================\r\n";
exMsg+="Date : "+(formatter.format(new Date()))+"\r\n\n";
exMsg+="reqString : "+request.getParameter("reqString")+"\r\n";
exMsg+="sign : "+request.getParameter("sign") +"\r\n";
exMsg+="ErrorMsg : "+exception+"\r\n\n";
exMsg+="ClassName : "+handlerMethod.getBean().getClass()+"\r\n\n";
exMsg+="MethodName : "+handlerMethod.getMethod().getName()+"\r\n\n";
exMsg+="Exception : "+handlerMethod +"\r\n\n";
LogerHelper.ApiLog(exMsg);
rm.setMessage(e.getMessage());
String json= JsonConvert.toJSON(rm);
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
}
return null;
}
}