springboot統一異常處理


  在做web應用時,請求過程中發生錯誤是常見的事,而一般界面顯示大片白底黑字讓人無從下手,對於用戶的體驗

也不是很好,這時我們可以利用@ControllerAdvice、@ExceptionHandler、@ResponseBody實現全局異常處理,能夠幫助

開發者或者客戶端迅速定位錯誤。

  步驟:

1.首先我們創建一個JSON返回對象,用來封裝{code:消息類型,url:請求地址,data:請求返回的數據,message:錯誤信息}

package com.wutongshu.springboot.domain;

public class ErrorInfo<E> {

    public static final int OK=0;

    public static  final int ERROR=100;

    private int code;
    private String url;
    private E data;
    private String message;


    public int getCode() {
        return code;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public E getData() {
        return data;
    }

    public void setData(E data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

2.創建一個自定義異常

package com.wutongshu.springboot.exception;

public class MyException extends Exception{
    public MyException(String message){
        super(message);
    }
}

3.在controller中增加測試異常的映射,拋出MyException異常

4.創建一個全局處理異常的類,

@ControllerAdvice 注解定義全局異常處理類

@ExceptionHandler  指定自定義錯誤處理方法攔截的異常類型

@ResponseBody 指返回JSON類型的數據

package com.wutongshu.springboot;

import com.wutongshu.springboot.domain.ErrorInfo;
import com.wutongshu.springboot.exception.MyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 處理異常類
 */
@ControllerAdvice
public class GlobalMyExceptionHandler {
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> handlerException(HttpServletRequest request,
                                              MyException e){
        ErrorInfo<String> errorInfo=new ErrorInfo<>();
        errorInfo.setMessage(e.getMessage());
        errorInfo.setUrl(request.getRequestURI());
        errorInfo.setCode(ErrorInfo.ERROR);
        errorInfo.setData("錯誤數據");
        return errorInfo;
    }

}

測試:訪問http://http://127.0.0.1:8087/test/testException,得到以下內容

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM