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