0
点赞
收藏
分享

微信扫一扫

SpringBoot/Cloud 统一返回优雅设计+自定义异常


SpringBoot/Cloud 统一返回优雅设计+自定义异常_工具类


SpringBoot/Cloud 统一返回优雅设计+自定义异常_返回结果_02

文章目录

  • ​​1. 返回结果封装​​
  • ​​2. 自定义异常​​
  • ​​3. 校验工具类​​
  • ​​4. 使用案例​​
  • ​​5. 前端效果图​​
1. 返回结果封装

package com.course.server.dto;

public class ResponseDto<T> {

/**
* 业务上的成功或失败
*/
private boolean success = true;

/**
* 返回码
*/
private String code;

/**
* 返回信息
*/
private String message;

/**
* 返回泛型数据,自定义类型
*/
private T content;

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public boolean getSuccess() {
return success;
}

public void setSuccess(boolean success) {
this.success = success;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public T getContent() {
return content;
}

public void setContent(T content) {
this.content = content;
}

@Override
public String toString() {
final StringBuffer sb = new StringBuffer("ResponseDto{");
sb.append("success=").append(success);
sb.append(", code='").append(code).append('\'');
sb.append(", message='").append(message).append('\'');
sb.append(", content=").append(content);
sb.append('}');
return sb.toString();
}
}

2. 自定义异常

package com.course.server.exception;

public class ValidatorException extends RuntimeException {

public ValidatorException(String message) {
super(message);
}
}

3. 校验工具类

package com.course.server.util;

import com.course.server.exception.ValidatorException;
import org.springframework.util.StringUtils;

public class ValidatorUtil {

/**
* 空校验(null or ""
*/
public static void require(Object str, String fieldName) {
if (StringUtils.isEmpty(str)) {
throw new ValidatorException(fieldName + "不能为空");
}
}

/**
* 长度校验
*/
public static void length(String str, String fieldName, int min, int max) {
if (StringUtils.isEmpty(str)) {
return;
}
int length = 0;
if (!StringUtils.isEmpty(str)) {
length = str.length();
}
if (length < min || length > max) {
throw new ValidatorException(fieldName + "长度" + min + "~" + max + "位");
}
}

}

4. 使用案例

@PostMapping("/save")
public ResponseDto save(@RequestBody ChapterDto chapterDto) {
// 保存校验
ValidatorUtil.require(chapterDto.getName(), "名称");
ValidatorUtil.require(chapterDto.getCourseId(), "课程ID");
ValidatorUtil.length(chapterDto.getCourseId(), "课程ID", 1, 8);

ResponseDto responseDto = new ResponseDto();
chapterService.save(chapterDto);
responseDto.setContent(chapterDto);
return responseDto;
}

5. 前端效果图

SpringBoot/Cloud 统一返回优雅设计+自定义异常_结果封装+自定义异常_03

SpringBoot/Cloud 统一返回优雅设计+自定义异常_工具类


SpringBoot/Cloud 统一返回优雅设计+自定义异常_返回结果_02


举报

相关推荐

0 条评论