@Data//lombok,包含get set 方法@AllArgsConstructor//有参构造@NoArgsConstructor//无参构造publicclassScofieldExecptionextendsRuntimeException{private Integer code;//状态码private String message;//异常信息}
异常处理Handler类
@ControllerAdvice//全局异常处理器publicclassGlobalExceptionHandler{@ExceptionHandler(Exception.class)//捕获异常类型@ResponseBodypublic Result error(Exception e){
e.printStackTrace();return Result.error().message("全局异常处理");}//自定义异常处理@ExceptionHandler(ScofieldExecption.class)//捕获异常类型@ResponseBodypublic Result error(ScofieldExecption e){
e.printStackTrace();return Result.error().message(e.getMessage()).code(e.getCode());//这里Result返回到前端也做成通用类型}}
统一通用返回类
/**
* 统一返回前端类,这种写法比较通用
*/@DatapublicclassResult{@ApiModelProperty(value ="是否成功")private Boolean success;@ApiModelProperty(value ="返回码")private Integer code;@ApiModelProperty(value ="返回消息")private String message;@ApiModelProperty(value ="返回数据")private Map<String,Object> data =newHashMap<String,Object>();private Result (){}publicstatic Result ok(){
Result r =newResult();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");return r;}publicstatic Result error(){
Result r =newResult();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");return r;}public Result data(String key,Object value){this.data.put(key,value);returnthis;}public Result data(Map<String,Object> map){this.setData(map);returnthis;}public Result code(Integer code){this.setCode(code);returnthis;}public Result success(Boolean success){this.setSuccess(success);returnthis;}public Result message(String message){this.setMessage(message);returnthis;}}