思路:
加一个拦截器,在preHandler中取得HandlerMethod,判断其方法的返回类型,以及方法的注解和类的注解。
如果返回是json,收到异常则返回默认的异常包装类型。
如果返回是页面,收到异常则返回默认的异常页面。
拦截器代码如下:
package com.xxx.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import java.lang.reflect.Method;
@Component
public class BaseInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod hm = (HandlerMethod) handler;
Method method = hm.getMethod();
boolean isPage = method.getReturnType().equals(String.class);
boolean isJosn = method.isAnnotationPresent(ResponseBody.class);
boolean isController = (!hm.getBeanType().isAnnotationPresent(RestController.class) && hm.getBeanType().isAnnotationPresent(Controller.class));
//controller_response_is_view 这个表示controller的返回响应类型是页面
request.setAttribute("method_return_is_view", isPage && !isJosn && isController);
return true;
}
}
全局异常处理ControllerAdvice代码如下:
package com.xxx.config;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
@Slf4j
public class CommonExceptionHandler {
@ExceptionHandler
public ModelAndView handleException(Exception exception, HttpServletRequest request, HttpServletResponse response) throws Exception{
log.error(exception.getMessage(), exception);
Object o = request.getAttribute("controller_response_is_view");
if( o == null) {
throw exception;
}
boolean isView = (Boolean)o;
if(isView){ //返回页面
//获取http状态码statusCode:401,404.jsp,500
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if(statusCode == 401){
return new ModelAndView("error/401");
}else if(statusCode == 403){
return new ModelAndView("error/403");
}else if(statusCode == 404){
return new ModelAndView("error/404");
}else{
return new ModelAndView("error/500");
}
}
//返回json
ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
mv.addObject("code","500");
mv.addObject("message",exception.getMessage());
return mv;
}
}
|