代码编织梦想

在前后端交互时,我们一般会统一接口的数据结构。

public class Result {

private Integer code;

private String message;

private T data;

}

code即定义接口的返回码,例如200对应请求成功

message即接口的返回信息,比如如果请求异常,message内就存放的异常信息

data则为具体需要的数据,这里使用T泛型,兼容所有返回类型

统一异常处理

我们首先构造一个Enum类来统一管理所有的异常分类:

public enum ExceptionEnum {

SUCCSEE(200,"请求成功"),

UNKNOW(-1000,"未知错误");

private Integer code;

private String message;

ExceptionEnum(Integer code,String message){

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;

}

}

因为我们的统一返回结果Result是有code以及message的,而默认的Exception没有code字段,所以接着构造一个异常基类来封装(注意继承RuntimeException而非Exception):

public class DemoException extends RuntimeException {

public DemoException(ExceptionEnum exceptionEnum) {

super(exceptionEnum.getMessage());

this.code = exceptionEnum.getCode();

}

private Integer code;

public Integer getCode() {

return code;

}

public void setCode(Integer code) {

this.code = code;

}

}

最后使用SpringBoot的@ControllerAdvice注解结合@ExceptionHandler注解对异常进行统一处理:

@ControllerAdvice

public class ExceptionHandle {

@ExceptionHandler(value =Exception.class)

@ResponseBody

public Result handle(Exception exception){

Result result=new Result();

if (exception instanceof DemoException){

result.setCode(((DemoException) exception).getCode());

}else {

DemoException demoException=new DemoException(ExceptionEnum.UNKNOW);

result.setCode(demoException.getCode());

}

result.setMessage(exception.getMessage());

return result;

}

}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/weixin_32448581/article/details/112878429