javascript
SpringBoot 统一异常处理 ControllerAdvice
轉(zhuǎn)載請標(biāo)明出處:http://blog.csdn.net/zhaoyanjun6/article/details/80678034
本文出自【趙彥軍的博客】
在用spring Boot做web后臺時,經(jīng)常會出現(xiàn)異常,如果每個異常都自己去處理很麻煩,所以我們創(chuàng)建一個全局異常處理類來統(tǒng)一處理異常。通過使用@ControllerAdvice定義統(tǒng)一的異常處理類,而不是在每個Controller中逐個定義。
ControllerAdvice
@ControllerAdvice,是Spring3.2提供的新注解,從名字上可以看出大體意思是控制器增強(qiáng)。
實(shí)例講解
下面我們通過一個例子,捕獲 IndexOutOfBoundsException 異常,然后統(tǒng)一處理這個異常,并且給用戶返回統(tǒng)一的響應(yīng)。
創(chuàng)建異常統(tǒng)一處理類: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 })@ResponseBodypublic 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 驗證一下。
統(tǒng)一處理自定義異常
自定義 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";} }自定義統(tǒng)一返回對象 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;} }創(chuàng)建異常統(tǒng)一處理類:ExceptionAdvice
@ControllerAdvice public class ExceptionAdvice {@ExceptionHandler({Exception.class})@ResponseBodypublic 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 , 歡迎關(guān)注
總結(jié)
以上是生活随笔為你收集整理的SpringBoot 统一异常处理 ControllerAdvice的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot AOP完全讲解二:
- 下一篇: SpringBoot 2.x 整合Myb