SpringBoot后端统一格式返回
统一结果一般形式:
- 状态码
- 描状态码述
- 响应数据
结果类枚举:
@Getter public enum ResultEnum { SUCCESS(200,"成功"), UNEXIST_URL(404,"URL不存在"), UNEXIST_ERROR(404,"用户不存在或密码有误"), UNKNOWN_ERROR(520,"未知错误"), SYSTEM_ERROR(500, "系统异常"), PARAM_ERROR(201,"参数错误"), NULL_POINTER(202,"空指针异常"); // 响应状态码 private Integer code; // 响应信息 private String message; ResultEnum(Integer code, String message) { this.code = code; this.message = message; } }
统一结果类:
@Accessors(chain = true) @Data public class Result { // 响应码 private Integer code; // 响应消息 private String message; // 响应数据 private Map<String, Object> data = new HashMap<>(); // 私有构造器 private Result() { } // 通用成功 public static Result ok() { return new Result() .setCode(ResultEnum.SUCCESS.getCode()) .setMessage(ResultEnum.SUCCESS.getMessage()); } // 通用失败 public static Result error() { return new Result() .setCode(ResultEnum.UNKNOWN_ERROR.getCode()) .setMessage(ResultEnum.UNKNOWN_ERROR.getMessage()); } // 自定义返回信息 public static Result setResult(ResultEnum result) { return new Result() .setCode(result.getCode()) .setMessage(result.getMessage()); } /** ------------使用链式编程,返回类本身-----------**/ // 自定义返回数据 public Result data(Map<String, Object> map) { this.setData(map); return this; } // 通用设置data public Result data(String key,Object value) { this.data.put(key, value); return this; } // 自定义状态信息 public Result message(String message) { this.setMessage(message); return this; } // 自定义状态码 public Result code(Integer code) { this.setCode(code); return this; } }
Controller统一结果返回:
统一异常处理:
@ControllerAdvice :该注解为统一异常处理的核心
自定义全局异常:
@Data @ToString public class CustomerDefinedException extends RuntimeException{ private Integer code; public CustomerDefinedException(Integer code, String message) { super(message); this.code = code; } public CustomerDefinedException(ResultEnum resultEnum) { super(resultEnum.getMessage()); this.code = resultEnum.getCode(); } }
统一异常处理器:
@Slf4j @ControllerAdvice public class GloablExceptionHandler { /**-------- 通用异常 --------**/ @ExceptionHandler(Exception.class) @ResponseBody public Result error(Exception e) { log.error("通用异常:" + e.getMessage()); return Result.setResult(ResultEnum.UNKNOWN_ERROR); } /**-------- 空指针异常 --------**/ @ExceptionHandler(NullPointerException.class) @ResponseBody public Result error(NullPointerException e) { log.error("空指针异常:" + e.getMessage()); System.out.println("空指针异常:" + e.getMessage()); return Result.setResult(ResultEnum.NULL_POINTER); } /**-------- 运行异常 --------**/ @ExceptionHandler(Throwable.class) @ResponseBody public Result error(Throwable e) { log.error("运行异常:" + e.getMessage()); System.out.println("运行异常:" + e.getMessage()); return Result.setResult(ResultEnum.SYSTEM_ERROR); } /**-------- 自定义异常 --------**/ @ExceptionHandler(CustomerDefinedException.class) @ResponseBody public Result error(CustomerDefinedException e) { log.error("自定义异常:" + e.getMessage()); return Result.error().message(e.getMessage()).code(e.getCode()); } /**-------- 算法异常 --------**/ @ExceptionHandler(ArithmeticException.class) @ResponseBody public Result error(ArithmeticException e) { log.error("算法异常:" + e.getMessage()); return Result.error().message(e.getMessage()); } /**-------- HTTP请求异常 --------**/ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody public Result error(HttpRequestMethodNotSupportedException e) { log.error("HTTP请求异常:" + e.getMessage()); return Result.error().message(e.getMessage()); } /**-------- 数据库操作异常 --------**/ @ExceptionHandler(DataAccessException.class) @ResponseBody public Result error(DataAccessException e) { log.error("数据库操作异常:" + e.getMessage()); return Result.error().message(e.getMessage()); } }
统一error处理(Web断跳404,500和error页面,非Web端统一JSON结果返回)
@Controller public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController { @Override public String getErrorPath() { return "/error"; } //针对浏览器端error异常处理--跳转403、404、500、error页面 @RequestMapping(value = "/error", produces = "text/html") public String errorPageHandler(HttpServletResponse response) { int status = response.getStatus(); switch (status) { case 403: return "403"; case 404: return "404"; case 500: return "500"; } return "error"; } //针对非浏览器端error异常处理(Postman,APP)--统一返回JSON结果 @RequestMapping("/error") @ResponseBody public Result handleError(HttpServletRequest request) { //获取statusCode:401,404,500 Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); return Result.setResult(ResultEnum.UNEXIST_URL).setCode(statusCode); } }
Web端跳404页面
非Web端统一JSON格式返回