1、搭建系统的目录结构
common目录用于存放全局的设置和内容。
-
annotation 注释信息
-
config 配置相关
-
constant 常数
-
core 核心 通用的类的信息。
-
enum 枚举类型
-
exception 异常信息
-
filter 过滤器
-
until 工具类
2、创建全局返回结果
JsonResult
package com.example.demo0108.common.core.model; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; /** * 统一返回数据结构 * * @author zfb * */ @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class JsonResult implements Serializable { private static final long serialVersionUID = -4177895470291082085L; @ApiModelProperty("成功标志:true成功 false失败") private boolean flag; // 响应业务状态 @ApiModelProperty("业务状态码") private String code; // 响应消息 @ApiModelProperty("业务提示") private String message; // 响应中的数据 @ApiModelProperty("数据") private Object data; public JsonResult() { } public JsonResult(boolean flag, String msg) { this.flag = flag; this.code = "00000"; //默认状态码为0000 this.message = msg; this.data = null; } public JsonResult(boolean flag, String code, String msg, Object data) { this.flag = flag; this.code = code; this.message = msg; this.data = data; } public JsonResult(Object data) { this.flag = true; this.code = "00000"; this.message = "success"; this.data = data; } public static JsonResult ok() { return new JsonResult(null); } public static JsonResult ok(String msg) { return new JsonResult(true, "00000", msg, null); } public static JsonResult ok(Object data) { return new JsonResult(data); } public static JsonResult ok(String msg, Object obj) { return new JsonResult(true, "00000", msg, obj); } //通用的错误放回编码 public static JsonResult error(String msg) { return new JsonResult(false, "-9999", msg, null); } public static JsonResult error(String code, String msg) { return new JsonResult(false, code, msg, null); } public static JsonResult error(String code, String msg, Object obj) { return new JsonResult(false, code, msg, obj); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JsonResult [flag=").append(flag).append(", code=").append(code).append(", message=").append(message) .append(", data=").append(data).append("]"); return builder.toString(); } } |
---|
新增方法测试异常类。
@ApiOperation(value = "测试统一返回类") @PostMapping("/springboot") public JsonResult index2(){ return JsonResult.ok("Welcome to the world of Spring Boot!"); } |
---|
在swagger内测试接口,测试成功。
3、整合全局捕获异常
创建全局异常类 GlobalExceptionHandler
@ExceptionHandler 表示拦截异常
- @ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
- @ControllerAdvice 可以指定扫描范围
- @ControllerAdvice 约定了几种可行的返回值,如果是直接返回 model 类的话,需要使用 @ResponseBody 进行 json 转换
package com.example.demo0108.common.exception; import com.example.demo0108.common.core.model.JsonResult; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.util.Set; /** * 全局捕获异常处理 * Created by Kong on 2019-06-28. * 处理po的入参代码的合理性。 */ @ControllerAdvice @Component @Slf4j public class GlobalExceptionHandler { @ExceptionHandler (ValidationException.class) //返回所有校验类异常时处理。 @ResponseBody //拦截返回是json结果 @ResponseStatus(HttpStatus.OK) public JsonResult handle(ValidationException exception) { JsonResult message = new JsonResult(); StringBuilder sb = new StringBuilder(); if (exception instanceof ConstraintViolationException) { ConstraintViolationException exs = (ConstraintViolationException) exception; Set<ConstraintViolation<?>> violations = exs.getConstraintViolations(); for (ConstraintViolation<?> item : violations) { /*不通过的信息拼接*/ sb.append(item.getMessage()).append(","); } } else { sb.append(exception.getMessage()); } message.setFlag(false); message.setMessage(deleteLastChar(sb.toString())); return message; } @ExceptionHandler(Exception.class) //返回所有的运行时异常。 @ResponseBody @ResponseStatus(HttpStatus.OK) public JsonResult handleException(Exception ex) { JsonResult response = new JsonResult(); response.setFlag(false); response.setCode("-9999"); //2019-09-11 @Kong json序列化异常 if (ex instanceof HttpMessageNotReadableException) { response.setMessage(ex.getCause().getMessage().split(" at ")[0]); }else { response.setMessage(ex.getMessage()); } log.error("系统发生异常:{}",ex); return response; } /** * 去掉最后一个字符。 返回异常时候,存在异常拼接,去除最后一个‘,’分隔符。 */ public static String deleteLastChar(String string) { if (string == null || string.equals("")) { return string; } return string.substring(0, string.length() - 1); } } |
---|