SpringBoot之自定義異常的兩種方式-yellowcong
阿新 • • 發佈:2019-02-18
Springboot異常的處理,可以通過一下幾種方法,1、使用@ControllerAdvice來進行統一異常處理,@ExceptionHandler(value = Exception.class)來指定捕獲的異常 ;2、通過自定義BasicErrorController 錯誤處理,這個是處理是基於狀態碼的。
程式碼地址
https://gitee.com/yellowcong/springboot-demo/tree/master/springboot-json
目錄結構
1、通過@ControllerAdvice
通過使用@ControllerAdvice來進行統一異常處理,@ExceptionHandler(value = Exception.class)來指定捕獲的異常 ,這個異常的處理,是全域性的,所有類似的異常,都會跑到這個地方處理
package com.yellowcong.exception;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
/**
* 建立日期:2018年4月6日<br/>
* 程式碼建立:黃聰<br/>
* 功能描述:<br/>
*/
@ControllerAdvice
public class RestExceptionHandler {
/**
* 建立日期:2018年4月6日<br/>
* 程式碼建立:黃聰<br/>
* 功能描述:直接處理 HttpMessageNotReadableException 報錯的資訊<br/>
* @param ex
* @return
*/
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public String requestNotReadable(HttpMessageNotReadableException ex){
ex.printStackTrace();
//json 資料讀取失敗
JSONObject result = new JSONObject();
result.put("code", 400);
result.put("msg", "json data is error ");
return result.toJSONString();
}
}
測試
當我們傳送錯誤的json資料後,直接報錯,而且這個錯誤並不是非常的友好,所以我們需要自定義異常來解決這個問題。
通過自定義錯誤後,解決的效果,返回的是自定義的錯誤訊息,這種效果好多了。
2、自定義BasicErrorController 錯誤處理
2.1啟動器新增EmbeddedServletContainerCustomizer
在啟動器裡面,新增EmbeddedServletContainerCustomizer
,然後在裡面註冊處理相應狀態碼的介面
package com.yellowcong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
@SpringBootApplication
public class ConfigMain {
public static void main(String[] args) {
SpringApplication.run(ConfigMain.class, args);
}
/**
* 建立日期:2018年4月6日<br/>
* 程式碼建立:黃聰<br/>
* 功能描述:錯誤的處理 <br/>
* @return
*/
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new EmbeddedServletContainerCustomizer(){
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
//404
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
//500錯誤
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
//400錯誤
container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/error/json"));
}
};
}
}
2.2錯誤處理控制器
這個控制器,和普通的控制器類似,沒有啥特別的,主要是用來處理狀態嗎對應的錯誤的檢視,這個地方需要說明的一點,json的404錯誤和直接通過瀏覽器訪問的404兩個的效果是不一樣的。
package com.yellowcong.error;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
/**
* 建立日期:2018年4月6日<br/>
* 程式碼建立:黃聰<br/>
* 功能描述:<br/>
*/
@Controller
@RequestMapping(value = "/error")
public class ExceptionController {
@RequestMapping(value = "/404")
@ResponseBody
public String error404(HttpServletRequest request) {
//json 資料讀取失敗
JSONObject result = new JSONObject();
result.put("code", 404);
result.put("msg", "Page not found ");
result.put("method", "error404");
return result.toJSONString();
}
/**
* 建立日期:2018年4月6日<br/>
* 程式碼建立:黃聰<br/>
* 功能描述:produces 表示只處理網頁直接傳送的請求<br/>
* @param request
* @param response
* @return
*/
@RequestMapping(produces = "text/html", value = "/404")
@ResponseBody
public String errorHtml404(HttpServletRequest request, HttpServletResponse response) {
//跳轉到error 目錄下的 404模板
return "介面沒有找到!!!";
}
/**
* 建立日期:2018年4月6日<br/>
* 程式碼建立:黃聰<br/>
* 功能描述:json讀取有問題的情況<br/>
* @param request
* @return
*/
@RequestMapping(value = "/json",produces="application/json;charset=UTF-8")
@ResponseBody
public String errorJson() {
//json 資料讀取失敗
JSONObject result = new JSONObject();
result.put("code", 400);
result.put("msg", "json data is error ");
result.put("method", "errorJson");
return result.toJSONString();
}
}
測試結果
測試中,我訪問的json錯誤,提示json有問題,當我直接通過josn訪問沒有的介面的時候,提示沒有找到,當直接通過瀏覽器訪問沒有找到的介面的時候,直接顯示的沒有找到,但是是我們的html的響應訊息。