当前位置:网站首页>全局异常处理器与统一返回结果
全局异常处理器与统一返回结果
2022-06-28 09:15:00 【多喝清晨的粥】
1、统一返回结果类
/** * @author * @ClassName: Result * @Description: 统一返回结果类 保证序列化json的时候,如果是null的对象,key也会消失 * @date 2021/9/18 15:32 */
@Data
public class Result<T> implements Serializable {
private Boolean success;
private Integer code;
private String message;
private T data;
public Result() {
}
private Result(Boolean success, Integer code) {
this.success = success;
this.code = code;
}
private Result(Boolean success, Integer code, T data) {
this.success = success;
this.code = code;
this.data = data;
}
private Result(Boolean success, Integer code, String message, T data) {
this.success = success;
this.code = code;
this.message = message;
this.data = data;
}
private Result(Boolean success, Integer code, String message) {
this.success = success;
this.code = code;
this.message = message;
}
public static <T> Result<T> success() {
return new Result<T>(true, ResponseEnum.SUCCESS.getCode(),ResponseEnum.SUCCESS.getMessage());
}
public static <T> Result<T> successMessage(String message) {
return new Result<T>(true, ResponseEnum.SUCCESS.getCode(), message);
}
public static <T> Result<T> success(T data) {
return new Result<T>(true, ResponseEnum.SUCCESS.getCode(),ResponseEnum.SUCCESS.getMessage(),data);
}
public static <T> Result<T> success(String message, T data) {
return new Result<T>(true, ResponseEnum.SUCCESS.getCode(), message, data);
}
public static <T> Result<T> error() {
return new Result<T>(false, ResponseEnum.ERROR.getCode(), ResponseEnum.ERROR.getMessage());
}
public static <T> Result<T> errorMessage(String errorMessage) {
return new Result<T>(false, ResponseEnum.ERROR.getCode(), errorMessage);
}
public static <T> Result<T> errorCodeMessage(Integer errorCode, String errorMessage) {
return new Result<T>(false, errorCode, errorMessage);
}
}
2、错误码枚举类
/** * @author * @ClassName: ResponseEnum * @Description: 响应状态码以及提示消息的枚举类型 * @date 2021/9/17 15:07 */
@Getter
public enum ResponseEnum {
SUCCESS(200,"操作成功"),
ERROR(500,"操作失败"),
INVALID_PARAM_ERROR(400,"无效的请求参数"),
;
private Integer code;
private String message;
ResponseEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
3、自定义异常处理类
/** * @author * @ClassName: CustomException * @Description: 自定义异常 * @date 2021/9/18 15:43 */
@Data
public class CustomException extends RuntimeException {
private Integer code;
public CustomException(ResponseEnum responseEnum) {
super(responseEnum.getMessage());
this.code = responseEnum.getCode();
}
public CustomException(ResponseEnum responseEnum, Throwable throwable) {
super(responseEnum.getMessage(), throwable);
this.code = responseEnum.getCode();
}
}
4、全局异常处理类
/** * @author * @ClassName: GlobalUniformException * @Description: 全局统一异常处理类 * @date 2021/9/18 15:48 */
@RestControllerAdvice
@Slf4j
public class GlobalUniformException {
/** * 处理自定义异常-------->指定某某方法要处理的异常类型 * @param e * @return */
@ExceptionHandler(CustomException.class)
public Result personalException(CustomException e){
e.printStackTrace();
return Result.errorCodeMessage(e.getCode(),e.getMessage());
}
/** * 处理自定义异常之外的其他异常 * @param e * @return */
@ExceptionHandler(Exception.class)
public Result handlerOtherException(Exception e){
e.printStackTrace();
return Result.errorCodeMessage(ResponseEnum.ERROR.getCode(),ResponseEnum.ERROR.getMessage());
}
}
5、测试返回统一结果
/** * @ * @ClassName: HelloController * @Description: 测试结果 * @date 2021/9/18 15:48 */
@RestController
@RequestMapping("/say")
public class HelloController {
@PostMapping("/hello")
public Result sayHello(User user){
if (StringUtils.isEmpty(user.getName())) {
return Result.errorMessage(ResponseEnum.ERROR.getMessage());
}
user.setName("小明");
user.setAge(20);
return Result.success(user);
}
}
浏览器测试结果:

postman浏览器测试结果:

6.测试抛出异常:
@RestController
@PostMapping("/say")
public class HelloController {
@RequestMapping("/hello")
public Result sayHello(User user){
User user = new User();
if (user.getName() == null) {
throw new CustomException(ResponseEnum.INVALID_PARAM_ERROR);
}
user.setName("小明");
user.setAge(20);
return Result.success(user);
}
}
postman测试失败结果:

浏览器测试失败结果:

边栏推荐
- 自动转换之-面试题
- Divide and rule classic Hanoi
- Common test method used by testers --- orthogonal method
- Which occupational groups are suitable for the examination
- Common faults and solutions of Substation
- Power data
- 批量修改表和表中字段排序规则
- SQL optimization experience: from 30248 seconds to 0.001 seconds
- Basic operation of PMP from applying for the exam to obtaining the certificate, a must see for understanding PMP
- Stock suspension
猜你喜欢

Calcul des frais d'achat et de vente d'actions

1181:整数奇偶排序

Characteristics and prevention of electrical fire

Ingersoll Rand面板维修IR英格索兰微电脑控制器维修XE-145M

数据挖掘建模实战

Application of energy management system in iron and steel enterprises

How to solve the problem of port number occupation

"Jianzhi offer" -- Interview Question 4: finding two-dimensional arrays

Discussion on safety management of centralized maintenance construction site of substation under the mode of operation and maintenance

SQL注入之文件读写
随机推荐
DEJA_ Vu3d - 052 of cesium feature set - Simulation of satellite orbit (high altitude) effect
How to reduce the risk of project communication?
Construire le premier réseau neuronal avec pytorch et optimiser
Implementation of single sign on
Which is a better ERP management system for electronic component sales?
Maintenance and protection of common faults of asynchronous motor
Installation of containerd1.5.5
玩玩sftp上传文件
股票 停牌
spark的资源调度和任务调度
硬盘基本知识(磁头、磁道、扇区、柱面)
P2394 yyy loves Chemistry I
Error: `brew cask` is no longer a `brew` command. Use `brew <command> --cask` instead.
1181:整数奇偶排序
redis5.0的槽点迁移,随意玩(单机迁移集群)
01-分布式系统概述
Play SFTP upload file
Why does select * lead to low query efficiency?
为什么SELECT * 会导致查询效率低?
Fire safety hazards