1、 我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理。
附加:创建封装错误状态码和错误消息VO
代码如下:
Result
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;@Data
@Schema(description = "响应结果实体类")
public class Result<T> {//返回码@Schema(description = "业务状态码")private Integer code;//返回消息@Schema(description = "响应消息")private String message;//返回数据@Schema(description = "业务数据")private T data;// 私有化构造private Result() {}// 返回数据public static <T> Result<T> build(T body, Integer code, String message) {Result<T> result = new Result<>();result.setData(body);result.setCode(code);result.setMessage(message);return result;}// 通过枚举构造Result对象public static <T> Result build(T body , ResultCodeEnum resultCodeEnum) {return build(body , resultCodeEnum.getCode() , resultCodeEnum.getMessage()) ;}}
ResultCodeEnum
import lombok.Getter;@Getter // 提供获取属性值的getter方法
public enum ResultCodeEnum {SUCCESS(200 , "操作成功"),LOGIN_ERROR(201 , "用户名或者密码错误"),VALIDATECODE_ERROR(202 , "验证码错误") ,LOGIN_AUTH(208 , "用户未登录"),USER_NAME_IS_EXISTS(209 , "用户名已经存在"),SYSTEM_ERROR(9999 , "您的网络有问题请稍后重试"),NODE_ERROR( 217, "该节点下有子节点,不可以删除"),DATA_ERROR(204, "数据异常"),ACCOUNT_STOP( 216, "账号已停用"),STOCK_LESS( 219, "库存不足"),;private Integer code ; // 业务状态码private String message ; // 响应消息private ResultCodeEnum(Integer code , String message) {this.code = code ;this.message = message ;}}
异常类:
创建自定义异常类
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import lombok.Data;
@SuppressWarnings("all")@Data
public class NiuException extends RuntimeException{private String message; // 错误消息private Integer code; // 错误状态码private ResultCodeEnum resultCodeEnum; // 封装错误状态码和错误消息publicNiuException(ResultCodeEnum resultCodeEnum){this.resultCodeEnum=resultCodeEnum;this.code= resultCodeEnum.getCode();this.message=resultCodeEnum.getMessage();}public NiuException(String message,Integer code){this.code=code;this.message=message;}}
全局异常处理器
在common-service中创建统一异常处理类GlobalExceptionHandler
// 处理自定义异常在GlobalExceptionHandler类上加自定义注解:@ExceptionHandler(value = NiuException.class)
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;/*** @ControllerAdvice 给controller增加统一的操作处理* 相当于是controller的增强器*/
@ControllerAdvice
public class GlobalExceptionHandler{/*** @ExceptionHandler(NiuException.class)出现异常的时候执行* @return* @ResponseBody 返回json格式*/// 处理自定义异常@ExceptionHandler(NiuException.class) @ResponseBodypublic Result error(NiuException e){return Result.build(null, e.getResultCodeEnum());}}