广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot封装响应处理超详细讲解
  • 375
分享到

SpringBoot封装响应处理超详细讲解

SpringBoot封装响应处理SpringBoot封装 2022-12-23 15:12:30 375人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录背景报文基本格式创建枚举类定义统一返回结果实体类定义返回工具类统一报文封装在接口中的使用统一异常处理小结背景 越来越多的项目开始基于前后端分离的模式进行开发,这对后端接口的报文格

背景

越来越多的项目开始基于前后端分离的模式进行开发,这对后端接口的报文格式便有了一定的要求。通常,我们会采用JSON格式作为前后端交换数据格式,从而减少沟通成本等。

报文基本格式

一般报文格式通常会包含状态码、状态描述(或错误提示信息)、业务数据等信息。 在此基础上,不同的架构师、项目搭建者可能会有所调整。 但从整体上来说,基本上都是大同小异。

SpringBoot项目中,通常接口返回的报文中至少包含三个属性:

code:请求接口的返回码,成功或者异常等返回编码,例如定义请求成功。

message:请求接口的描述,也就是对返回编码的描述。

data:请求接口成功,返回的业务数据。

示例报文如下:

{
  "code":200,
  "message":"SUCCESS",
  "data":{
   "info":"测试成功"
  }
}

在上述报文格式中,不同的设计者是会有一些分歧的,特别是code值的定义。如果完全基于RESTful api设计的话,code字段可能就不需要存在了,而是通过Http协议中提供的GET、POST、PUT、DELETE操作等来完成资源的访问。

但在实践中,不论是出于目前国内大多数程序员的习惯,还是受限于HTTP协议提供的操作方法的局限性,很少完全遵照RESTful API方式进行设计。通常都是通过自定义Code值的形式来赋予它业务意义或业务错误编码。

虽然可以不用完全遵守RESTful API风格来定义Code,在Code值的自定义中,也存在两种形式:遵循HTTP状态码和自主定义。

像上面的示例,用200表示返回成功,这就是遵循HTTP响应状态码的形式来返回,比如还有其他的400、401、404、500等。当然,还有完全自主定义的,比如用0表示成功,1表示失败,然后再跟进通用编码、业务分类编码等进行定义。

在此,笔者暂不评论每种形式的好坏,只列举了常规的几种形式,大家了解对应的情况,做到心中有数,有所选择即可。

创建枚举类

用于定义返回的错误码:

public enum ErrorCode {
    SUCCESS(0, "ok", ""),
    FaiL(500, "failed",""),
    PARAMS_ERROR(40000, "请求参数错误", ""),
    NULL_ERROR(40001, "请求数据为空", ""),
    NOT_LOGIN(40100, "未登录", ""),
    NO_AUTH(40101, "无权限", ""),
    SYSTEM_ERROR(50000, "系统内部异常", "");
    private final int code;
    
    private final String message;
    
    private final String description;
    ErrorCode(int code, String message, String description) {
        this.code = code;
        this.message = message;
        this.description = description;
    }
    public int getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
    public String getDescription() {
        return description;
    }
}

定义统一返回结果实体类

@Data
public class BaseResponse<T> implements Serializable {
    private int code;
    private T data;
    private String message;
    private String description;
    public BaseResponse(int code, T data, String message, String description) {
        this.code = code;
        this.data = data;
        this.message = message;
        this.description = description;
    }
    public BaseResponse(int code, T data, String message) {
        this(code, data, message, "");
    }
    public BaseResponse(int code, T data) {
        this(code, data, "", "");
    }
    public BaseResponse(ErrorCode errorCode) {
        this(errorCode.getCode(), null, errorCode.getMessage(), errorCode.getDescription());
    }
}

在BaseResponse中运 用了泛型和公共方法、构造方法的封装,方便在业务中使用。 示例中只提供了部分方法的封装,根据自身业务场景和需要可进一步封装。

定义返回工具类

public class ResultUtils {
    
    public static <T> BaseResponse<T> success(T data) {
        return new BaseResponse<>(ErrorCode.SUCCESS.getCode(), data, "ok");
    }
    public static <T> BaseResponse<T> success(String message) {
        return new BaseResponse<>(ErrorCode.SUCCESS.getCode(), null, message);
    }
    
    public static BaseResponse error(ErrorCode errorCode) {
        return new BaseResponse<>(errorCode);
    }
    
    public static BaseResponse error(int code, String message, String description) {
        return new BaseResponse(code, null, message, description);
    }
    
    public static BaseResponse error(ErrorCode errorCode, String message, String description) {
        return new BaseResponse(errorCode.getCode(), null, message, description);
    }
    
    public static BaseResponse error(ErrorCode errorCode, String description) {
        return new BaseResponse(errorCode.getCode(), errorCode.getMessage(), description);
    }
    public static BaseResponse error(String message) {
        return new BaseResponse(ErrorCode.FAIL.getCode(),message);
    }
    
    public static BaseResponse error(httpstatus errorCode, String description) {
        return new BaseResponse(errorCode.value(), errorCode.getReasonPhrase(), description);
    }
}

统一报文封装在接口中的使用

@RestController
public class TestController {
  @RequestMapping("/calc")
  public ResponseInfo<String> calc(Integer id) {
    try {
      // 模拟异常业务代码
      int num = 1 / id;
      log.info("计算结果num={}", num);
      return ResultUtils.success();
    } catch (Exception e) {
      return ResponseInfo.error("系统异常,请联系管理员!");
    }
  }
}

统一异常处理

在上述实例中,我们通过try…catch的形式捕获异常,并进行处理。 在springBoot中,我们可以通过RestControllerAdvice注解来定义全局异常处理,这样就无需每处都try…catch了。


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    public BaseResponse businessExceptionHandler(BusinessException e) {
        log.error("businessException: " + e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage(), e.getDescription());
    }
    @ExceptionHandler(RuntimeException.class)
    public BaseResponse runtimeExceptionHandler(RuntimeException e) {
        log.error("runtimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage(), "");
    }
    
    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResponse badRequestException(IllegalArgumentException ex) {
        log.error("参数格式不合法:{}", ex.getMessage());
        return ResultUtils.error(HttpStatus.BAD_REQUEST, "参数格式不符!");
    }
    
    @ExceptionHandler({AccessDeniedException.class})
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public BaseResponse badRequestException(AccessDeniedException ex) {
        return ResultUtils.error(HttpStatus.FORBIDDEN, ex.getMessage());
    }
    
    @ExceptionHandler({MissingServletRequestParameterException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResponse badRequestException(Exception ex) {
        return ResultUtils.error(HttpStatus.BAD_REQUEST, "缺少必填参数!");
    }
    
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse handleTypeMismatchException(NullPointerException ex) {
        log.error("空指针异常,{}", ex.getMessage());
        return ResultUtils.error("空指针异常");
    }
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse handleUnexpectedServer(Exception ex) {
        log.error("系统异常:", ex);
        return ResultUtils.error("系统发生异常,请联系管理员");
    }
    
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse exception(Throwable throwable) {
        log.error("系统异常", throwable);
        return ResultUtils.error(HttpStatus.INTERNAL_SERVER_ERROR, "系统异常,请联系管理员!");
    }
}

在上述方法中,对一些常见的异常进行了统一处理。 通常情况下,根据业务需要还会定义业务异常,并对业务异常进行处理,大家可以根据自己项目中异常的使用情况进行拓展。

关于@RestControllerAdvice的几点说明:

@RestControllerAdvice注解包含了@Component注解,会把被注解的类作为组件交给Spring来管理。

@RestControllerAdvice注解包含了@ResponseBody注解,异常处理完之后给调用方输出一个jsON格式的封装数据。

@RestControllerAdvice注解有一个basePackages属性,该属性用来拦截哪个包中的异常信息,一般不指定,拦截项目工程中的所有异常。

在方法上通过@ExceptionHandler注解来指定具体的异常,在方法中处理该异常信息,最后将结果通过统一的JSON结构体返回给调用者。

重构接口

@RestController
public class TestController {
  @RequestMapping("/calc")
  public ResponseInfo<String> calc(Integer id) {
         // 模拟异常业务代码
      int num = 1 / id;
      log.info("计算结果num={}", num);
      return ResultUtils.success();
     }
}

在请求的时候,不传递id值,即在浏览器中访问:

{
  "code": 500,
  "data": "空指针异常",
  "message": "",
  "description": ""
}

可以看到统一异常处理对空指针异常进行了拦截处理,并返回了ExceptionHandlerAdvice中定义的统一报文格式。

小结

在使用SpringBoot或其他项目中,统一的报文格式和统一的异常处理都是必须的。 本篇文章介绍了基于SpringBoot的实现,如果你的项目中采用了其他的技术栈,则可考虑对应的处理方式。 同时,日常中很多类似的功能都可以统一进行处理,避免大量无效的硬编码。

到此这篇关于SpringBoot封装响应处理超详细讲解的文章就介绍到这了,更多相关SpringBoot封装响应处理内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot封装响应处理超详细讲解

本文链接: https://www.lsjlt.com/news/175670.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作