SpringBoot 統一異常處理 ControllerAdvice

轉載請標明出處:http://blog.csdn.net/zhaoyanjun6/article/details/80678034
本文出自【趙彥軍的博客】

在用spring Bootweb後臺時,經常會出現異常,如果每個異常都自己去處理很麻煩,所以我們創建一個全局異常處理類來統一處理異常。通過使用@ControllerAdvice定義統一的異常處理類,而不是在每個Controller中逐個定義。

ControllerAdvice

@ControllerAdvice,是Spring3.2提供的新註解,從名字上可以看出大體意思是控制器增強。

實例講解

下面我們通過一個例子,捕獲 IndexOutOfBoundsException 異常,然後統一處理這個異常,並且給用戶返回統一的響應。

創建異常統一處理類:ExceptionAdvice

package com.yiba.didiapi.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler({ IndexOutOfBoundsException.class })
    @ResponseBody
    public String handleIndexOutOfBoundsException(Exception e) {
        e.printStackTrace();
        return "testArrayIndexOutOfBoundsException";
    }

}

定義 ApiController

@RestController
public class ApiController {

    @GetMapping("getUser")
    public String getUser() {
        List<String> list = new ArrayList<>();
        return list.get(2);
    }

}

可以看到在 getUser 方法中, 會拋出 IndexOutOfBoundsException 異常。但是這個異常不會通過接口拋給用戶,會被 ExceptionAdvice 類攔截,下面我們用 postMan 驗證一下。

這裏寫圖片描述

統一處理自定義異常

自定義 GirlException 異常

public class GirlException extends RuntimeException {

    private Integer code;

    public GirlException(Integer code, String msg) {
        super(msg);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

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

}

controller 裏面拋出異常,新建ApiController

@RestController
public class ApiController {

    @GetMapping("getUser/{id}")
    public String getUser(@PathVariable("id") Integer id) {
        if (id == 0) {
            throw new GirlException(101, "年齡太小了");
        } else if (id == 1) {
            throw new GirlException(102, "年齡不夠18歲");
        }
        return "ok";
    }
}

自定義統一返回對象 ResultUtil

public class ResultUtil {

    int code;
    String mes;

    public ResultUtil(int code, String mes) {
        this.code = code;
        this.mes = mes;
    }

    public int getCode() {
        return code;
    }

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

    public String getMes() {
        return mes;
    }

    public void setMes(String mes) {
        this.mes = mes;
    }
}

創建異常統一處理類:ExceptionAdvice

@ControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ResultUtil handleIndexOutOfBoundsException(Exception e) {
        ResultUtil resultUtil;
        if (e instanceof GirlException) {
            GirlException girlException = (GirlException) e;
            resultUtil = new ResultUtil(girlException.getCode(), girlException.getMessage());
            return resultUtil;
        }
        return new ResultUtil(0, "未知異常");
    }
}

測試

這裏寫圖片描述


個人微信號:zhaoyanjun125 , 歡迎關注

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章