SpringMVC爲controller錯誤作統一處理

1 項目中常常出現遇到RuntimeException,須要給出一個默認返回JSONjava

2 使用 @ControllerAdvice,不用任何的配置,只要把這個類放在項目中,Spring能掃描到的地方。就能夠實現全局異常的回調。web

代碼以下:spring

package cc.messcat.common.exception;數據庫

import java.util.HashMap;
import java.util.Map;apache

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;json

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;session

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.util.LogUtil;app

import com.alibaba.fastjson.support.spring.FastJsonJsonView;this


@ControllerAdvice
public class WebExceptionHandler{spa

     /** 
     * 全局處理Exception 
     * 錯誤的狀況下返回500 
     * @param ex 
     * @param req 
     * @return 
     */  
    @ExceptionHandler(value = {Exception.class})  
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {  
        HandlerMethod hm = (HandlerMethod) handler;
        String className = hm.getBeanType().getSimpleName();
        String method = hm.getMethod().getName();
        StringBuffer buffer = new StringBuffer(className);
        buffer.append(".").append(method).append(" exception: ");
        LogUtil.logException(buffer.toString(), ex);
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("status", CommonConstant.EXCEPTION_CODE_500);
        attributes.put("message", CommonConstant.MSG_FAIL);
        view.setAttributesMap(attributes);
        mv.setView(view);
        return mv;  
    } 


    /** 
     * 業務處理BizException 
     * @param ex 
     * @param req 
     * @return 
     */  
    @ExceptionHandler(value = {BizException.class})  
    public ModelAndView resolveBizException(HttpServletRequest request,BizException ex) {  
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("status", ex.getCode());
        attributes.put("message", ex.getMsg());
        view.setAttributesMap(attributes);
        mv.setView(view);
        return mv;  
    }  

}
 

BizException定義:

package cc.messcat.common.exception;

/**
 * 
 * ClassName: BizException 
 * @Description: 業務異常基類,全部業務異常都必須繼承於此異常
 * @author limh
 * @date 2017年3月11日
 */
public class BizException extends RuntimeException {

    private static final long serialVersionUID = -5875371379845226068L;

    /**
     * 數據庫操做,insert返回0
     */
    public static final BizException DB_INSERT_RESULT_0 = new BizException(
            20010001, "數據庫操做,insert返回0");

    /**
     * 數據庫操做,update返回0
     */
    public static final BizException DB_UPDATE_RESULT_0 = new BizException(
            20010002, "數據庫操做,update返回0");

    /**
     * 數據庫操做,selectOne返回null
     */
    public static final BizException DB_SELECTONE_IS_NULL = new BizException(
            20010003, "數據庫操做,selectOne返回null");

    /**
     * 數據庫操做,list返回null
     */
    public static final BizException DB_LIST_IS_NULL = new BizException(
            20010004, "數據庫操做,list返回null");

    /**
     * Token 驗證不經過
     */
    public static final BizException TOKEN_IS_ILLICIT = new BizException(
            20010005, "Token 驗證非法");

    /**
     * 會話超時 獲取session時,若是是空,throws 下面這個異常 攔截器會攔截爆會話超時頁面
     */
    public static final BizException SESSION_IS_OUT_TIME = new BizException(
            20010006, "會話超時");

    /**
     * 異常信息
     */
    protected String msg;

    /**
     * 具體異常碼
     */
    protected int code;

    public BizException(int code, String msgFormat, Object... args) {
        super(String.format(msgFormat, args));
        this.code = code;
        this.msg = String.format(msgFormat, args);
    }

    public BizException() {
        super();
    }

    public String getMsg() {
        return msg;
    }

    public int getCode() {
        return code;
    }

    /**
     * 實例化異常
     * 
     * @param msgFormat
     * @param args
     * @return
     */
    public BizException newInstance(String msgFormat, Object... args) {
        return new BizException(this.code, msgFormat, args);
    }

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

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

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

BaseException定義:

/**
 * Description: <br/>
 */
package cc.messcat.common.exception;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * ClassName: BaseException 
 * @Description: TODO
 * @author limh
 * @date 2017年3月11日
 */
public class BaseException extends BizException {

    private static final long serialVersionUID = 662981704729484572L;

    private static final Log log = LogFactory.getLog(BaseException.class);

    /**
     * 異常code
     */
    public final static int TICKET_NOTE_TYPE_IS_NOT_AVAILABLE = 21040031;
    
    public BaseException() {
    }

    public BaseException(int code, String msgFormat, Object... args) {
        super(code, msgFormat, args);
    }

    public BaseException(int code, String msg) {
        super(code, msg);
    }

    /**
     * 實例化異常
     * 
     * @param msgFormat
     * @param args
     * @return
     */
    public BaseException newInstance(String msgFormat, Object... args) {
        return new BaseException(this.code, msgFormat, args);
    }

    public BaseException print() {
        log.info("==>BizException, code:" + this.code + ", msg:" + this.msg);
        return new BaseException(this.code, this.msg);
    }
}

調用例子:

Route route = routeTravelAppService.getRouteInfo(routeId); if(route == null ){     throw new BaseException(BaseException.TICKET_NOTE_TYPE_IS_NOT_AVAILABLE,"行程爲空"); }
相關文章
相關標籤/搜索