import lombok.Getter;/**
* 自定义异常
*/
@Getter
public class ServiceException extends RuntimeException {
private String code;
public ServiceException(String code, String msg){super(msg);
this.code = code;}}
定义全局异常处理器
import com.example.shopsystemspringboot.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 {/**
* 如果抛出的的是ServiceException,则调用该方法
* @param se 业务异常
* @return Result
*/
@ExceptionHandler(ServiceException.class)
@ResponseBody
public Result handle(ServiceException se){return Result.error(se.getCode(), se.getMessage());}}
封装后端接口请求的返回类
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(){returnnewResult("200","", null);}
public static Result success(Object data){returnnewResult("200","", data);}
public static Result error(String code, String msg){returnnewResult(code, msg, null);}
public static Result error(){returnnewResult("500","系统错误", null);}}