
阿松大
构架截图
result.java
package com.qgx.demo.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private String code;
private String msg;
private Object data;
public static Result success() {
return new Result(Constants.CODE_200, "", null);
}
public static Result success(Object data) {
return new Result(Constants.CODE_200, "", data);
}
public static Result error(String code, String msg) {
return new Result(code, msg, null);
}
public static Result error() {
return new Result(Constants.CODE_500, "系统错误", null);
}
}
Constants.java(常量类,定义Code) 接口
package com.qgx.demo.common;
public interface Constants {
String CODE_200 = "200"; //成功
String CODE_401 = "401"; // 权限不足
String CODE_400 = "400"; // 参数错误
String CODE_500 = "500"; // 系统错误
String CODE_600 = "600"; // 其他业务异常
String Session_key="";
}
GlobalExceptionHandler.java
package com.qgx.demo.exception;
import com.qgx.demo.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
//ExceptionHandler 统一处理某一类异常
@ExceptionHandler(value = ServiceException.class)
@ResponseBody
public Result handle(ServiceException se){
return Result.error(se.getCode(), se.getMessage());
}
}
ServiceException.java(自定义业务异常)
package com.qgx.demo.exception;
import lombok.Getter;
@Getter
public class ServiceException extends RuntimeException{
private String code;
public ServiceException(String code, String msg) {
super(msg);
this.code = code;
}
}