1. 程式人生 > >@ControllerAdvice + @ExceptionHandler 全域性處理 Controller 層異常(轉)

@ControllerAdvice + @ExceptionHandler 全域性處理 Controller 層異常(轉)

需求
在構建RestFul的今天,我們一般會限定好返回資料的格式比如:

{

  "code": 0,
  "data": {},
  "msg": "操作成功"
}

但有時卻往往會產生一些bug。這時候就破壞了返回資料的一致性,導致呼叫者無法解析。所以我們常常會定義一個全域性的異常攔截器。
注意:ControllerAdvice註解 只攔截Controller 不回攔截 Interceptor的異常

介紹
在spring 3.2中,新增了@ControllerAdvice 註解,用於攔截全域性的Controller的異常,注意:ControllerAdvice註解只攔截Controller不會攔截Interceptor的異常

程式碼

package com.cmc.schedule.handler;
 
import com.gionee.base.entity.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.io.IOException;
 
/**
 * 異常攔截處理器
 *
 * @author chenmc
 */
@ControllerAdvice
@ResponseBody (@ResponseBody加上否則不起效果)
public class GlobalExceptionHandler {
 
    private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";
    private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 
    //執行時異常  
    @ExceptionHandler(RuntimeException.class)
    public String runtimeExceptionHandler(RuntimeException ex) {
        return resultFormat(1, ex);
    }
 
    //空指標異常  
    @ExceptionHandler(NullPointerException.class)
    public String nullPointerExceptionHandler(NullPointerException ex) {
        return resultFormat(2, ex);
    }
 
    //型別轉換異常  
    @ExceptionHandler(ClassCastException.class)
    public String classCastExceptionHandler(ClassCastException ex) {
        return resultFormat(3, ex);
    }
 
    //IO異常  
    @ExceptionHandler(IOException.class)
    public String iOExceptionHandler(IOException ex) {
        return resultFormat(4, ex);
    }
 
    //未知方法異常  
    @ExceptionHandler(NoSuchMethodException.class)
    public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {
        return resultFormat(5, ex);
    }
 
    //陣列越界異常  
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
        return resultFormat(6, ex);
    }
 
    //400錯誤  
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public String requestNotReadable(HttpMessageNotReadableException ex) {
        System.out.println("400..requestNotReadable");
        return resultFormat(7, ex);
    }
 
    //400錯誤  
    @ExceptionHandler({TypeMismatchException.class})
    public String requestTypeMismatch(TypeMismatchException ex) {
        System.out.println("400..TypeMismatchException");
        return resultFormat(8, ex);
    }
 
    //400錯誤  
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public String requestMissingServletRequest(MissingServletRequestParameterException ex) {
        System.out.println("400..MissingServletRequest");
        return resultFormat(9, ex);
    }
 
    //405錯誤  
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public String request405(HttpRequestMethodNotSupportedException ex) {
        return resultFormat(10, ex);
    }
 
    //406錯誤  
    @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
    public String request406(HttpMediaTypeNotAcceptableException ex) {
        System.out.println("406...");
        return resultFormat(11, ex);
    }
 
    //500錯誤  
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    public String server500(RuntimeException ex) {
        System.out.println("500...");
        return resultFormat(12, ex);
    }
 
    //棧溢位
    @ExceptionHandler({StackOverflowError.class})
    public String requestStackOverflow(StackOverflowError ex) {
        return resultFormat(13, ex);
    }
 
    //其他錯誤
    @ExceptionHandler({Exception.class})
    public String exception(Exception ex) {
        return resultFormat(14, ex);
    }
 
    private <T extends Throwable> String resultFormat(Integer code, T ex) {
        ex.printStackTrace();
        log.error(String.format(logExceptionFormat, code, ex.getMessage()));
        return JsonResult.failed(code, ex.getMessage());
    }
 
}  
package com.cmc.base.entity;
 
import com.alibaba.fastjson.JSON;
import lombok.Data;
 
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author chenmc
 * @date 2017/10/12 17:18
 */
@Data
public class JsonResult implements Serializable{
 
    private int code;   //返回碼 非0即失敗
    private String msg; //訊息提示
    private Map<String, Object> data; //返回的資料
 
    public JsonResult(){};
 
    public JsonResult(int code, String msg, Map<String, Object> data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
 
    public static String success() {
        return success(new HashMap<>(0));
    }
    public static String success(Map<String, Object> data) {
        return JSON.toJSONString(new JsonResult(0, "解析成功", data));
    }
 
    public static String failed() {
        return failed("解析失敗");
    }
    public static String failed(String msg) {
        return failed(-1, msg);
    }
    public static String failed(int code, String msg) {
        return JSON.toJSONString(new JsonResult(code, msg, new HashMap<>(0)));
    }
 
}

Spring Boot這樣就可以了,如果是沒用Spring Boot的話,需要在SpringMvc的配置檔案中增加下面的配置

<!-- 處理異常 -->
    <context:component-scan base-package="com.gionee.xo" use-default-filters="false">  
        <!-- base-package 如果多個,用“,”分隔 -->  
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />  
        <!--控制器增強,使一個Contoller成為全域性的異常處理類,類中用@ExceptionHandler方法註解的方法可以處理所有Controller發生的異常-->  
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />  
    </context:component-scan>