1.自定义异常处理类
** * 自定义异常处理类 * 针对不同的异常自定义不同的方法 * 环绕通知 * 切面:针对所有的controller中抛出的异常 * 若使用@ControllerAdvice,则不会自动转换为JSON格式 */ @RestControllerAdvice public class RestExceptionHandler {
/** * 业务异常处理 * @param e * @return ErrorInfo */ @ExceptionHandler({BaseBusinessException.class}) public ErrorInfo BusinessExceptionHandler(BaseBusinessException e) { return new ResponseResultUtil().error(e.getCode(), e.getMessage()); }
} 2.定义一个用于返回页面结果信息的VO对象类:ErrorInfo
public class ErrorInfo { private Integer code; private String message; public ErrorInfo(){}; public ErrorInfo(Integer code, String message) { super(); this.code = code; this.message = message; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
3.封装一个基础业务异常类(让所有自定义业务异常类 继承此 基础类):BaseBusinessException
/** * 类名称: BaseBusinessException * 类描述: 业务异常父类 * 创建人:GMM * date 2019/3/11 */ public class BaseBusinessException extends RuntimeException { private Integer code; // 给子类用的方法 public BaseBusinessException(HttpStatus httpStatus) { this(httpStatus.value(),httpStatus.getReasonPhrase()); } public BaseBusinessException(Integer code,String message) { super(message); this.code = code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } } 4.service 层抛出
@Service public class UserLoginServiceImpl implements UserLoginService { @Autowired private UserLoginRepsitory userLoginRepsitory; @Transactional @Override public boolean login(String userCode, String password) { Employee employee=userLoginRepsitory.getEmployeeByCode(userCode); if(StringUtils.isBlank(userCode)){ throw new BaseBusinessException(101,"用户名不能为空"); } }