springmvc配置统一异常处理器+自定义异常

36套java进阶高级架构师视频+38套大数据视频  保证全是硬货需要的

+微信:

du13797566440


创建统一返回的json对象

public class AjaxResponse{

/**

*/
private static final long serialVersionUID = 1L;



private int code; 
/** 状态对应的描述 **/
private String msg;

/** 扩展字段 **/
private String extMsg;
/** 需要返回的信息 **/
private Object result;

private Pager page;

public int getCode() {
return code;
}


public void setCode(int code) {
this.code = code;
}


public String getMsg() {
return msg;
}


public void setMsg(String msg) {
this.msg = msg;
}


public Object getResult() {
return result;
}


public void setResult(Object result) {
this.result = result;
}


/**
* @return the page
*/
public Pager getPage() {
return page;
}


/**
* @param page the page to set
*/
public void setPage(Pager page) {
this.page = page;
}


/**
* @return the extMsg
*/
public String getExtMsg() {
return extMsg;
}


/**
* @param extMsg the extMsg to set
*/
public void setExtMsg(String extMsg) {
this.extMsg = extMsg;
}

}


/**
 * AJAX请求状态返回值
 */
public enum EnumAjaxResponseStatus {


/** 成功 **/
SUCCESS(0),

/** 失败 **/
FAIL(-1),

/** 网络异常 **/
NETERROR(-9);


private int status;


private EnumAjaxResponseStatus(int status) {
this.status = status;
}


public int getStatus() {
return status;
}


public void setStatus(int status) {
this.status = status;
}


}

------------------------------------------------

自定义异常类

public class PermissionException extends RuntimeException {

private AjaxResponse AjaxResponse;
    public AjaxResponse getAjaxResponse() {
return AjaxResponse;
}


public void setAjaxResponse(AjaxResponse AjaxResponse) {
this.AjaxResponse = AjaxResponse;
}


public PermissionException(AjaxResponse AjaxResponse) {
        super();
    }


    public PermissionException(String message) {
        super(message);
    }


    public PermissionException(String message, Throwable cause) {
        super(message, cause);
    }


    public PermissionException(Throwable cause) {
        super(cause);
    }


    protected PermissionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}


import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/*
 * 
 * 描述:要一引入codehaus依赖
 * <!-- jackson -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
 * 作者: dlj
 * 时间: 2018年1月16日 上午9:22:45
 * 
 */
public class JsonMapper {
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
    private static ObjectMapper objectMapper = new ObjectMapper();


    static {
        // config
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
    }


    public static <T> String obj2String(T src) {
        if (src == null) {
            return null;
        }
        try {
            return src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
        } catch (Exception e) {
        logger.warn("parse object to String exception, error:{}", e);
            return null;
        }
    }


    public static <T> T string2Obj(String src, TypeReference<T> typeReference) {
        if (src == null || typeReference == null) {
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference));
        } catch (Exception e) {
        logger.warn("parse String to Object exception, String:{}, TypeReference<T>:{}, error:{}", src, typeReference.getType(), e);
            return null;
        }
    }


    public static Map<String, Object> objectToMap(Object obj) throws Exception {    
        if(obj == null)  
            return null;      
  
        Map<String, Object> map = new HashMap<String, Object>();   
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
        for (PropertyDescriptor property : propertyDescriptors) {    
            String key = property.getName();    
            if (key.compareToIgnoreCase("class") == 0) {   
                continue;  
            }  
            Method getter = property.getReadMethod();  
            Object value = getter!=null ? getter.invoke(obj) : null;  
            map.put(key, value);  
        }    
  
        return map;  
    }  
}

------------------------------------------------

异常处理器

import java.lang.reflect.Method;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.AnnotationUtils;
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 org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class  SpringExceptionResolver implements HandlerExceptionResolver {


    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
      
        ModelAndView mv;
        String defaultMsg = "System error";
        
        // 转成springmvc底层对象(就是对action方法的封装对象,只有一个方法)
      HandlerMethod handlerMethod = (HandlerMethod) handler;
      // 取出方法
      Method method = handlerMethod.getMethod();
      // 判断方法是否返回json
      // 只要方法上有responsebody注解表示返回json
      // 查询method是否有responsebody注解
      ResponseBody responseBody = AnnotationUtils.findAnnotation(method,
      ResponseBody.class);
      JsonData resolveExceptionCustom = resolveExceptionCustom(ex,request,method);
      if (responseBody != null) {
      // 将异常信息转json输出
      MappingJackson2JsonView view = new MappingJackson2JsonView();
            view.setAttributesMap(resolveExceptionCustom.toMap());
mv = new ModelAndView();
mv.setView(view);
      }else{
          mv = new ModelAndView("error/exception", resolveExceptionCustom.toMap());//exception为jsp页面名
      }
      return mv;
    }
    
 // 异常信息解析方法
  private JsonData resolveExceptionCustom(Exception ex,HttpServletRequest request,Method method) {
  JsonData resultInfo = null;
  String url = request.getRequestURL().toString();
      Map<String, String[]> parameterMap = request.getParameterMap();
  if (ex instanceof PermissionException) {
  // 抛出的是系统自定义异常
  resultInfo = ((PermissionException) ex).getJsonData();
 
  } else {
  // 重新构造“未知错误”异常
  resultInfo = JsonData.fail("未知错误!",1);
  log.error("unknown exception, url:{},ex:{} method:{} parameterMap:{}," , url, ex,method.getName(),JsonMapper.obj2String(parameterMap));
  }


  return resultInfo;


  }
}

-----------------------------------------

spring中添加配置

<bean id="exceptionHandler" class="com.zte.web.filter.SpringExceptionResolver" />

猜你喜欢

转载自blog.csdn.net/adudeboke/article/details/79070736