自定义异常
/**
* @Author ccyy
* @Date 2023-05-31 10:21
**/
public class ServiceException extends Exception{
private static final long serialVersionUID = -1219262335729891920L;
public ServiceException(String message) {
super(message);
}
public ServiceException(Throwable cause) {
super(cause);
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
}
统一异常处理类
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ErrorConfig {
@ExceptionHandler({ServiceException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public R handleError(ServiceException e) {
return R.fail(HttpStatus.BAD_REQUEST.value(), e.getMessage());
}
}
使用
throw new ServiceException("账号错误");