SpringBoot的@ControllerAdvice處理全局異常詳解
@ControllerAdvice處理全局異常
需求
在構(gòu)建RestFul的今天,我們一般會(huì)限定好返回?cái)?shù)據(jù)的格式比如:
{<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->
??????? "code": 0,
"data": {},
"msg": "操作成功"
}但有時(shí)卻往往會(huì)產(chǎn)生一些bug。這時(shí)候就破壞了返回?cái)?shù)據(jù)的一致性,導(dǎo)致調(diào)用者無法解析。
所以我們常常會(huì)定義一個(gè)全局的異常攔截器。
注意:ControllerAdvice注解 只攔截Controller 不回?cái)r截 Interceptor的異常
介紹
在spring 3.2中,新增了@ControllerAdvice 注解,用于攔截全局的Controller的異常,注意:ControllerAdvice注解只攔截Controller不會(huì)攔截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
public class GlobalExceptionHandler {
private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";
private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
//運(yùn)行時(shí)異常
@ExceptionHandler(RuntimeException.class)
public String runtimeExceptionHandler(RuntimeException ex) {
return resultFormat(1, ex);
}
//空指針異常
@ExceptionHandler(NullPointerException.class)
public String nullPointerExceptionHandler(NullPointerException ex) {
return resultFormat(2, ex);
}
//類型轉(zhuǎn)換異常
@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);
}
//數(shù)組越界異常
@ExceptionHandler(IndexOutOfBoundsException.class)
public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
return resultFormat(6, ex);
}
//400錯(cuò)誤
@ExceptionHandler({HttpMessageNotReadableException.class})
public String requestNotReadable(HttpMessageNotReadableException ex) {
System.out.println("400..requestNotReadable");
return resultFormat(7, ex);
}
//400錯(cuò)誤
@ExceptionHandler({TypeMismatchException.class})
public String requestTypeMismatch(TypeMismatchException ex) {
System.out.println("400..TypeMismatchException");
return resultFormat(8, ex);
}
//400錯(cuò)誤
@ExceptionHandler({MissingServletRequestParameterException.class})
public String requestMissingServletRequest(MissingServletRequestParameterException ex) {
System.out.println("400..MissingServletRequest");
return resultFormat(9, ex);
}
//405錯(cuò)誤
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
public String request405(HttpRequestMethodNotSupportedException ex) {
return resultFormat(10, ex);
}
//406錯(cuò)誤
@ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
public String request406(HttpMediaTypeNotAcceptableException ex) {
System.out.println("406...");
return resultFormat(11, ex);
}
//500錯(cuò)誤
@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);
}
//其他錯(cuò)誤
@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; //返回的數(shù)據(jù)
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 如果多個(gè),用“,”分隔 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<!--控制器增強(qiáng),使一個(gè)Contoller成為全局的異常處理類,類中用@ExceptionHandler方法注解的方法可以處理所有Controller發(fā)生的異常-->
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>到此這篇關(guān)于SpringBoot的@ControllerAdvice處理全局異常詳解的文章就介紹到這了,更多相關(guān)@ControllerAdvice處理全局異常內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot整合Spring Security的詳細(xì)教程
這篇文章主要介紹了SpringBoot整合Spring Security的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
java根據(jù)網(wǎng)絡(luò)地址保存圖片的方法
這篇文章主要為大家詳細(xì)介紹了java根據(jù)網(wǎng)絡(luò)地址保存圖片的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
Mybatis實(shí)現(xiàn)自定義類型轉(zhuǎn)換器TypeHandler的方法
Mybatis實(shí)現(xiàn)自定義的轉(zhuǎn)換器非常的簡(jiǎn)單,只需要三步就可以實(shí)現(xiàn)自定義類型轉(zhuǎn)換器TypeHandler,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看下吧2016-07-07
SpringBoot整合mybatis-plus實(shí)現(xiàn)分頁查詢功能
這篇文章主要介紹了SpringBoot整合mybatis-plus實(shí)現(xiàn)分頁查詢功能,pringBoot分頁查詢的兩種寫法,一種是手動(dòng)實(shí)現(xiàn),另一種是使用框架實(shí)現(xiàn),現(xiàn)在我將具體的實(shí)現(xiàn)流程分享一下,需要的朋友可以參考下2023-11-11
利用Intellij Idea連接遠(yuǎn)程服務(wù)器實(shí)現(xiàn)遠(yuǎn)程上傳部署功能
大家在使用Intellij Idea開發(fā)程序的時(shí)候,是不是需要部署到遠(yuǎn)程SSH服務(wù)器運(yùn)行呢,當(dāng)然也可以直接在idea軟件內(nèi)容實(shí)現(xiàn)配置部署操作,接下來通過本文給大家分享利用Intellij Idea連接遠(yuǎn)程服務(wù)器實(shí)現(xiàn)遠(yuǎn)程上傳部署功能,感興趣的朋友跟隨小編一起看看吧2021-05-05
詳解Java中ThreadLocal類型及簡(jiǎn)單用法
ThreadLocal實(shí)例通常是希望將狀態(tài)與線程關(guān)聯(lián)起來的類中的私有靜態(tài)字段,下面通過例子給大家詳細(xì)介紹Java中ThreadLocal類型及簡(jiǎn)單用法,感興趣的朋友跟隨小編一起看看吧2021-10-10
關(guān)于HashMap相同key累加value的問題
這篇文章主要介紹了關(guān)于HashMap相同key累加value的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05

