java自定义异常及异常的抛出

时间:2019-11-20
本文章向大家介绍java自定义异常及异常的抛出,主要包括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一般是根据各公司不同的使用情况进行综合定义,后端只需调用即可。
 

原文地址:https://www.cnblogs.com/gemiaomiao/p/11900564.html