一.用處:
當前端訪問接口時,後端在拋出異常返回時,一般http的狀態碼爲500,而前端的理想接收數據爲:http狀態碼爲200,表示請求成功,而異常返回的數據應該例爲:code:400,message:找不到資源。
在controller層拋出異常時,異常處理器可以進行捕獲然後根據自己的設定進行返回
二.優點:
1.對不同業務異常進行多樣化處理(狀態碼設置,異常信息封裝)
2.可以對服務器原來的異常封裝(空指針異常、服務器異常等等)
三.實現:
1.自定義一個異常類:
public class CrePipServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
private static final String ID_ERROR = "token異常:";
private String errCode;
private String errMessage;
public CrePipServiceException(String errCode, String errMessage) {
super(errMessage);
this.errCode = errCode;
this.errMessage = errMessage;
}
public static CrePipServiceException notEmpty(String name) {
return new CrePipServiceException("1000102",NOT_NULL + name);
}
}
2.定義異常處理器
@ControllerAdvice
public class PipeGlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(PipeGlobalExceptionHandler.class);
/**
* 處理自定義的業務異常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = CrePipServiceException.class)
@ResponseBody
public ResultBody pipeExceptionHandler(HttpServletRequest req, CrePipServiceException e){
logger.error("發生業務異常!原因是:{}",e.getErrMessage());
return ResultBody.error(e.getErrCode(),e.getErrMessage());
}
}
3.在controller層拋出異常
@GetMapping("/getComponents")
public RestResponse<List> getComponentsList(@RequestParam String namespace, @RequestParam String component) {
if (namespace == null || "".equals(namespace)) {
throw CrePipServiceException.notEmpty("namespace");
}
if (component == null || "".equals(component)) {
throw CrePipServiceException.notEmpty("component");
}
List result = this.componentService.getProjectComponent(namespace, component);
return RestResponse.<List>builder().data(result).build();
}
4.查看返回信息
四.遇到的問題:
1.@ControllerAdvice註解不生效
狀態碼一直不對,返回信息也不對,最開始以爲是全局變量不對,後來又以爲是異常類沒定義好,胡整一通,都沒用,後來查了一下博客,有人說是spring沒掃描到,需要加@SpringBootApplication(scanBasePackages = {"com.test.admin","com.test.admin.exception"}
但是還是沒生效,後來才發現我的全局異常處理類名字爲GlobalExceptionHandler,可能被覆蓋了,於是改成了PipGlobalExceptionHandler名,結果就好了 (😂,浪費了一整天時間在這上面~~~~~)
2.異常信息一直爲null
由於自定義的異常類繼承的RuntimeException,所以自定義的異常類構造方法需要super(errMessage)