java自定義異常及異常的拋出


在項目的開發過程中前后端一般會遇到很多的異常,這些異常的處理后端通常會通過throw出一個對象,前端再將接收到的異常對象code和message進行二次判斷

或直接將message顯示給用戶,用戶再去操作界面。

后端對於異常的定義及處理

一.首先定義一個返回的異常對象

public class BaseBusinessException extends RuntimeException {


private Integer code;

   private String message;

public BaseBusinessException(Integer code,String message) {
super(message);
this.code = code;
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}
}
二.定義一個自定義的異常處理類,方便對各種類型的異常進行拋出。
/**
* 自定義異常處理類
* 針對不同的異常自定義不同的方法
* 環繞通知
* 切面:針對所有的controller中拋出的異常
* 若使用@ControllerAdvice,則不會自動轉換為JSON格式
*/
@RestControllerAdvice
public class RestExceptionHandler {

/**
* 業務異常處理
* @param e
* @return ErrorInfo
*/
@ExceptionHandler({BaseBusinessException.class})
public ResponseEntity<ErrorInfo> businessExceptionHandler(HttpServletRequest request,BaseBusinessException e) throws BaseBusinessException {
return new ResponseEntity(new ErrorInfo(e.getCode(),e.getMessage()), HttpStatus.CONFLICT);
}

/**
* 業務異常處理
* @param e
* @return ErrorInfo
*/
@ExceptionHandler({AccessDeniedException.class})
public ResponseEntity<ErrorInfo> BusinessExceptionHandler(HttpServletRequest request, AccessDeniedException e) throws BaseBusinessException {
return new ResponseEntity(new ErrorInfo(401, e.getMessage()), HttpStatus.UNAUTHORIZED);
}

/**
* 只要拋出該類型異常,則由此方法處理
* 並由此方法響應出異常狀態碼及消息
* 如:RoleController.getRoleById(String id)方法
* @param request
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
public ResponseEntity<ErrorInfo> handleException(HttpServletRequest request, Exception e) throws Exception {

ErrorInfo body = new ErrorInfo();
body.setCode(500);
body.setMessage(e.getMessage());

//可以根據公司情況不同,類似的異常可能需要不同的狀態碼
ResponseEntity<ErrorInfo> responseEntity = new ResponseEntity<ErrorInfo>(body, HttpStatus.INTERNAL_SERVER_ERROR);
return responseEntity;
}

}
三.在業務處理過程中(一般是Service類中),遇到已知的,需要向客戶端展示的業務異常,通過throw一個自己定義的異常對象拋出異常。
public void updatePassword(String userCode,String oldPassword,String newPassword,String newNextPassword){
Employee employee=employeeRepository.findEmployeeByCode(userCode);
if(null == employee){
throw new BaseBusinessException(409,"用戶不存在");
}
if(!newPassword.equals(newNextPassword)){
throw new BaseBusinessException(409,"兩次新密碼輸入不一致");
}

}
四,在異常的對象返回值中code一般是根據各公司不同的使用情況進行綜合定義,后端只需調用即可。
 


免責聲明!

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



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