利用try catch 來throw錯誤 預防後端報錯導致前端無法正常顯示
阿新 • • 發佈:2020-12-23
技術標籤:Spring bootjava
不寫try catch 親人兩行淚
要從controller層 到 service層 通通要寫try catch
@POST
@Path("xxx")
public ResponseBean exportTransExcpOrder(TransExcProcessQueryVo vo) {
ResponseBean responseBean = new ResponseBean();
try {
// 這service裡面可能會報錯
orderService. exportListTransExcpOrder(vo, userId);
responseBean.setStatus(StatusConstants.SUCCESS);
responseBean.setErrMsg(MessageConstants.TASK_SUBMIT);
} catch (ServiceBizException e) {
// catahc 業務報錯 是一些預料到的報錯
logger.error(e.getErrorMessage());
responseBean = new ResponseBean(StatusConstants.FAIL, null,
e.getErrorMessage());
} catch (Exception e) {
// 沒有預料到的錯誤統一丟擲系統異常
logger.error(e.getMessage(), e);
responseBean.setStatus(StatusConstants.FAIL);
responseBean.setErrMsg("系統異常" );
}
return responseBean;
}
這裡順便存一下 非同步生成表格的一個操作 asyncUtil
這裡呼叫util裡面的handleInput 方法 這方法裡面會丟擲業務異常 我們也要接住
@Override
public void exportListTransExcpOrder(TransExcProcessQueryVo queryVo, String userId) {
AttachmentVo attachment = new AttachmentVo();
try {
// 查詢條件input超過200個
List<String> inputList = BusinessUtil.handleInput(queryVo.getInput());
// 區分input是多值查詢,還是單個查詢
if (inputList != null) {
queryVo.setInputList(inputList);
queryVo.setInput(null);
}
對於單個輸入/多個輸入,我們的處理方法是判斷出來是多個之後放進list裡面
} catch (ServiceBizException e) {
// 捕捉業務邏輯錯誤
logger.error(e.getErrorMessage(), e);
asyncUtil.complete(AsyncOptEnum.TRANS_EXCP_EXPORT, userId,
new ResponseBean(StatusConstants.FAIL, e.getErrorMessage()));
throw e;
} catch (Exception e) {
// 捕捉非業務錯誤
logger.error(e.getMessage(), e);
asyncUtil.complete(AsyncOptEnum.TRANS_EXCP_EXPORT, userId,
new ResponseBean(StatusConstants.FAIL, e.getMessage()));
throw e;
}
asyncUtil.complete(AsyncOptEnum.TRANS_EXCP_EXPORT, userId,
new ResponseBean(StatusConstants.SUCCESS, attachment, MessageConstants.OPERATE_SUCCESS));
}
這個util對輸入做了一個處理,可以支援多個輸入,可以根據空格,分號,逗號分開
public static List<String> handleInput(String input) {
if (input == null || input.length() < 17) {
return null;
}
input = input.replaceAll("[\\s|,|;]*", "");
String newInput = input.replaceAll("(.{17})", "$1,");
List<String> inputList = Arrays.asList(newInput.split(","));
if (inputList.size() > 200) {
// 這裡丟擲了一個 serviceBizException 業務邏輯異常 是我們預測到的使用者會煩的錯誤
throw new ServiceBizException("0", "最多支援200個Input查詢");
}
return inputList;
}