SpringMVC實現全局異常捕獲處理

需求:在SpringMVC中實現全局異常捕獲解析以及處理而且返回json狀態碼
需求分析解決:
一、進入Spring-MVC配置文件配置全局異常處理java

<!-- 全局異常處理  自定義實現spring的全局異常解析器HandlerExceptionResolver -->
    <bean id="exceptionResolver" class="com.xxx.resolver.CustomExceptionResolver"></bean>複製代碼

二、定義全局異常處理類web

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.xxx.bean.Result;
import com.xxx.excption.CustomException;
import com.xxx.util.ResultUtils;
/**
 * 全局異常處理器
 * @author CatalpaFlat
 */
public class CustomExceptionResolver implements HandlerExceptionResolver{  
    /**日誌log*/
    private static Logger log = LoggerFactory.getLogger(CustomExceptionResolver.class);

    //系統拋出的異常  
    @Override  
    public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex) {  
        //handler就是處理器適配器要執行的Handler對象(只有method)  
        //解析出異常類型。  
        /*  使用response返回    */  
        response.setStatus(HttpStatus.OK.value()); //設置狀態碼  
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //設置ContentType  
        response.setCharacterEncoding("UTF-8"); //避免亂碼  
        response.setHeader("Cache-Control", "no-cache, must-revalidate");  
        //若是該 異常類型是系統 自定義的異常,直接取出異常信息。  
        CustomException customException=null;  
        try {
            if(ex instanceof CustomException){  
                customException = (CustomException)ex;  
                //錯誤信息  
                response.getWriter().write(ResultUtils.error(customException.getCode(),ex.getMessage()).toString());
            }else
                response.getWriter().write(ResultUtils.error(-1,ex.getMessage()).toString());
        } catch (IOException e) {
            log.error("與客戶端通信異常:"+ e.getMessage(), e);  
            e.printStackTrace();
        }
        ModelAndView modelAndView=new ModelAndView();  

        return modelAndView;  
    }  

}複製代碼

三、自定義異常類CustomExceptionspring

import com.xxx.enums.ResultEnum;
/**
 * 自定義異常類型
 * @author CatalpaFlat
 */
public class CustomException extends Exception {

    private Integer code;
    public CustomException(){}

    public CustomException(ResultEnum resultEnum) {
        super((resultEnum.getMsg()));
        this.code = resultEnum.getCode();
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
}複製代碼

四、定義Http響應json類json

/** 
 * http請求返回的最外層
 * Created by CatalpaFlat 
 * on 2017/4/12.
 */
public class Result<T> {
    private Integer code;
    private String msg;
    private T data;
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    @Override
    public String toString() {
        return "{\"code\": "+code+",\"msg\": \""+msg+"\",\"data\": "+data+"}";
    }

}複製代碼

五、定義http返回json的ResulUtilsbash

import com.xxx.bean.Result;
/** 
 * http請求返回success以及error方法封裝
 * Created by CatalpaFlat 
 * on 2017/4/12.
 */
public class ResultUtils {
    private static final String SUCCESS_MSG = "成功";
    /**
     * http回調成功
     * @param object
     * @return
     */
    public  static Result success(Object object){
        Result result = new Result();
        result.setCode(1);
        result.setMsg(SUCCESS_MSG);
        result.setData(object);
        return result;
    }
    /**
     * 無object返回
     * @return
     */
    public  static Result success(){
        return success(null);
    }
    /**
     * http回調錯誤
     * @param code
     * @param msg
     * @return
     */
    public static Result error(Integer code,String msg){
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return  result;
    }

}複製代碼

六、定義異常類型枚舉ResultEnumapp

/**
 * 枚舉定義異常類型以及相對於的錯誤信息
 * 有助於返回碼的惟一性
 * Created by CatalpaFlat  
 * on 2017/4/12.
 */
public enum ResultEnum {

    UNKONW_ERROR(-1,"未知錯誤"),
    SUCCESS(0,"成功"),
    TEST_ERRORR(100,"測試異常");

    private Integer code;
    private String msg;
    ResultEnum(Integer code,String msg){
        this.code = code;
        this.msg = msg;
    }
    public Integer getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
}複製代碼

七、測試TestControlleride

@Controller
@RequestMapping("/teco")
public class TestController {
    @RequestMapping(value = "/testexc",method = RequestMethod.GET)
    @ResponseBody
    public void testException() throws CustomException{
        throw new CustomException(ResultEnum.TEST_ERRORR);
    }
}複製代碼

八、測試接口json返回
測試

相關文章
相關標籤/搜索