记录一下SpringBoot中使用自定义异常操作方法,代码如下;
创建ServiceException.class
public class ServiceException extends RuntimeException{
private int code = 500;
public ServiceException() { }
public ServiceException(String message) {
super(message);
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
public ServiceException(Throwable cause) {
super(cause);
}
public ServiceException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public ServiceException(int code) {
this.code = code;
}
public ServiceException(String message, int code) {
super(message);
this.code = code;
}
public ServiceException(String message, Throwable cause,
int code) {
super(message, cause);
this.code = code;
}
public ServiceException(Throwable cause, int code) {
super(cause);
this.code = code;
}
public ServiceException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace, int code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
public int getCode() {
return code;
}
}
创建ExceptionControllerAdvice.class
import com.lyxl.common.project.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {
@ExceptionHandler
public String handlerServiceException(ServiceException e){
log.error("业务异常",e);
return e.getMessage();
}
@ExceptionHandler
public String handlerException(Exception e){
log.error("其它异常",e);
return e.getMessage();
}
}
在业务中使用
if (users.size() > 1) {
throw new ServiceException("用户数量大于1!");
}
if (null!=user.getPhone) {
throw new Exception("电话号已注册,请您登陆!");
}
捕获异常
userService.registerStudent(registerVo);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)