1. 程式人生 > 實用技巧 >【轉】 SpringBoot統一異常處理

【轉】 SpringBoot統一異常處理

【轉】 SpringBoot統一異常處理

  一:在實際開發中,當我們程式報錯時,不是直接顯示錯誤內容給使用者,一般都會統一跳轉到錯誤頁面。定義一個異常方法,如下:

    @RequestMapping("/exception")
    public String exception() throws Exception{
      throw new Exception("error");
    }

  顯示結果如下:這是springboot提供的預設error對映頁面。

  

  二:統一異常處理(返回錯誤頁面)

  (1)建立全域性異常處理類,如下:

package springboot.web;

import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value
= Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e){ ModelAndView modelAndView =new ModelAndView(); modelAndView.addObject("exception",e); modelAndView.addObject("url",req.getRequestURI()); modelAndView.setViewName("error");
return modelAndView; } }

  使用@ControllerAdvice定義統一的異常處理類,@ExceptionHandler用來定義函式針對的異常型別,最後跳轉到error.html。

  三:統一異常處理(返回json格式)

  (1)如果要返回json格式,只需要在@ExceptionHandler下新加一個@ResponseBody註解即可,如下:

    //統一返回json錯誤資訊
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, Exception e){
        ErrorInfo<String> r = new ErrorInfo<String>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("Return jsonException");
        r.setUrl(req.getRequestURI());
        return r;
    }

  (2)建立統一的Json返回物件,如下:

public class ErrorInfo <T>{

    public static final Integer OK =0;
    public static final Integer ERROR=100;
    
    private Integer code; //訊息型別
    private String message;//訊息內容
    private String url;//請求的url
    private T data;//請求返回的資料
    
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    
}

  (3)啟動postman,呼叫方法,返回如下: