SpringBoot定义优雅全局统一Restful API 响应框架三

Posted kenx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot定义优雅全局统一Restful API 响应框架三相关的知识,希望对你有一定的参考价值。

我们目前已经设计出了,包含全局响应,异常错误响应进行了统一返回。但是错误内容我们设计的比较模糊统一,还可以进行细化这样更有利于定位错误

当我们需要调用Http接口时,无论是在Web端还是移动端,都有可能遇到各种错误,例如参数缺失、类型错误、系统错误等。为了规范错误信息的返回,我们需要定义一个统一的接口错误返回值。通过对接口错误返回值的统一设计,我们可以规范调用方对各种不同错误的处理方式,并提供更加详细、准确的错误提示,同时也帮助后端实现接口返回值的规范化设计。因此,接口错误返回值的设计不仅仅是对错误信息的规范化处理,还涉及到业务上的错误设计。这样的设计可以有效地提高接口的使用效率和可维护性。

错误码定义

根据 http stats 错误通常可以分为以下几大类

  1. 200:请求成功
  2. 400:请求参数错误
  3. 401:未授权访问
  4. 403:表示禁止访问资源。
  5. 404:表示未找到资源。
  6. 500:表示服务器内部错误。

错误码的设计,可以借用http错误码+三位api自定义错误码 一共是6位数字,具体每个模块代表什么可以根据你自己的业务逻辑,定义不同数字,位数对应不同模块

对应错误格式如下

错误接口

package cn.soboys.springbootrestfulapi.common.error;

/**
 * @author 公众号 程序员三时
 * @version 1.0
 * @date 2023/5/2 21:33
 * @webSite https://github.com/coder-amiao
 * 错误码接口,凡各模块错误码枚举类,皆须为此接口的子类型
 */
public interface ErrorCode 
    Integer getCode();

    String getMessage();

    boolean getSuccess();

自定义错误实现枚举

package cn.soboys.springbootrestfulapi.common.error;

/**
 * @author 公众号 程序员三时
 * @version 1.0
 * @date 2023/5/2 21:36
 * @webSite https://github.com/coder-amiao
 */
public enum CommonErrorCode implements ErrorCode 

    NOT_FOUND(false, 404, "接口不存在"),
    FORBIDDEN(false, 403, "资源拒绝访问"),
    UNAUTHORIZED(false, 401, "未认证(签名错误)"),
    INTERNAL_SERVER_ERROR(false, 500, "服务网络不可用"),
    PARAM_ERROR(false, 110001, "参数错误");



    CommonErrorCode(Boolean success, Integer code, String message) 
        this.success = success;
        this.code = code;
        this.message = message;

    

    /**
     * 响应是否成功
     */
    private Boolean success;
    /**
     * 响应状态码
     */
    private Integer code;
    /**
     * 响应信息
     */
    private String message;


    @Override
    public Integer getCode() 
        return code;
    

    @Override
    public String getMessage() 
        return message;
    

    @Override
    public boolean getSuccess() 
        return success;
    




全局异常错误处理

package cn.soboys.springbootrestfulapi.common.exception;


import cn.hutool.core.collection.CollectionUtil;
import cn.soboys.springbootrestfulapi.common.error.CommonErrorCode;
import cn.soboys.springbootrestfulapi.common.resp.R;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 公众号 程序员三时
 * @version 1.0
 * @date 2023/4/29 00:21
 * @webSite https://github.com/coder-amiao
 * 统一异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler 

    /**
     * 通用异常处理方法
     **/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e, WebRequest request) 
        e.printStackTrace();
        return R.setResult(CommonErrorCode.INTERNAL_SERVER_ERROR)
                .request(request.getDescription(true))
                .errorMsg(e.getMessage());
    



    /**
     * 处理 form data方式调用接口对象参数校验失败抛出的异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R BindExceptionHandler(BindException e) 
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return R.failure().code(CommonErrorCode.PARAM_ERROR.getCode()).message(message);
    

    /**
     * 处理Get请求中 验证路径中 单个参数请求失败抛出异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R ConstraintViolationExceptionHandler(ConstraintViolationException e) 
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return R.failure().code(CommonErrorCode.PARAM_ERROR.getCode()).message(message);
    


    /**
     * 处理 json 请求体调用接口对象参数校验失败抛出的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R jsonParamsException(MethodArgumentNotValidException e) 
        BindingResult bindingResult = e.getBindingResult();
        String msg=";";

        for (FieldError fieldError : bindingResult.getFieldErrors()) 
             msg = String.format("%s%s;", fieldError.getField(), fieldError.getDefaultMessage())+msg;
        
        return R.failure().code(CommonErrorCode.PARAM_ERROR.getCode()).message(msg);
    

    /**
     * 自定义异常处理方法
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public R error(BusinessException e) 
        e.printStackTrace();
        return R.failure().message(e.getMessage()).code(e.getCode());
    



具体项目代码已经 同步到github 上,后续会完善更新一系列整合脚手架工具,能够开箱即用

SpringBoot RESTful API返回统一数据格式还不懂?

关于 Spring 的全局处理,有两方面要说:

统一数据返回格式
统一异常处理
为了将两个问题说明清楚,将分两个章节分别说明,本章主要说第一点
有童鞋说,我们项目都做了这种处理,就是在每个 API 都单独工具类将返回值进行封装,但这种不够优雅;我想写最少的代码完成这件事,也许有童鞋说,加几个注解就解决问题了,说的没错,但这篇文章主要是为了说明为什么加了几个注解就解决问题了,目的是希望大家知其所以然。

为了更好的说明问题,本文先说明如何实现,然后再详细剖析实现原理(这很关键)

为什么要做统一数据返回格式

前后端分离是当今服务形式的主流,如何让前端小伙伴可以处理标准的 response JSON 数据结构都至关重要,为了让前端有更好的逻辑展示与页面交互处理,每一次 RESTful 请求都应该包含以下几个信息:

名称

描述

status

状态码,标识请求成功与否,如 [1:成功;-1:失败]

errorCode

错误码,给出明确错误码,更好的应对业务异常;请求成功该值可为空

errorMsg

错误消息,与错误码相对应,更具体的描述异常信息

resultBody

返回结果,通常是 Bean 对象对应的 JSON 数据, 通常为了应对不同返回值类型,将其声明为泛型类型 实现

通用返回值类定义

根据上面的描述,用 Java Bean 来体现这个结构就是这样:

@Data

public final class CommonResult<T> {

private int status = 1;

private String errorCode = "";

private String errorMsg = "";

private T resultBody;

public CommonResult() {

}

public CommonResult(T resultBody) {

SpringBoot RESTful API返回统一数据格式还不懂?
SpringBoot RESTful API返回统一数据格式还不懂?

}

}

配置

没错,我们需要借助几个关键注

@EnableWebMvc

@Configuration

public class UnifiedReturnConfig {

@RestControllerAdvice("com.example.unifiedreturn.api")

static class CommonResultResponseAdvice implements ResponseBodyAdvice<Object>{

@Override

public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {

return true;

}

@Override

public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

if (body instanceof CommonResult){

return body;

}

return new CommonResult<Object>(body);

}

}

}

dy);

}

}

}

到这里就结束了,我们就可以纵情的写任何 RESTful API 了,所有的返回值都会有统一的 JSON

@RestController

@RequestMapping("/users")

public class UserController {

@GetMapping("")

public List<UserVo> getUserList(){

List<UserVo> userVoList = Lists.newArrayListWithCapacity(2);

userVoList.add(UserVo.builder().id(1L).name("一米八的一小伙").age(18).build());

userVoList.add(UserVo.builder().id(2L).name("tan").age(19).build());

return userVoList;

}

}

lder().id(2L).name("tan").age(19).build());

return userVoList;

}

}

}

@GetMapping("/{id}")

public UserVo getUserByName(@PathVariable Long id){

return UserVo.builder().id(1L).name("一米八的一小伙").age(18)

getUserByName(@PathVariable Long id){

return UserVo.builder().id(1L).name("一米八的一小伙").age(18).

e("一米八的一小伙").age(18).

@GetMapping("/testResponseEntity")

public ResponseEntity getUserByAge(){

return new ResponseEntity(UserVo.builder().id(1L).name("一米八的一小伙").age(18).build(), H

ty getUserByAge(){

return new ResponseEntity(UserVo.builder().id(1L).name("一米八的一小伙").age(18).build(), HttpStatus.OK);

}

d(), HttpStatus.OK);

}

打开浏览器输入地址测试: http://localhost:8080/users/testR

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

@Documented

@Import(DelegatingWebMvcConfiguration.class)

public

icy.RUNTIME)

@Target(ElementType.TYP

ME)

@Target(ElementType.TYPE)

@Doc

TYPE)

@Doc

@Configuration

public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

...

}

引入了 DelegatingWebMvcConfiguration.class,那来看这个类吧:

@Configurat

@Bean

public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {

RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();

...

return adapter;

}

lic RequestMappingHandlerAdapte

public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter

implements BeanFactoryAware, InitializingBean {

...

}

RequestMappingHandlerAdapter 是每一次请求处理的关键,来看该类的定义:

public class RequestMappingHandlerAdapter extends AbstractHandle

@Override

public void afterPropertiesSet() {

// Do this first, it may add ResponseBody advice beans

initControllerAdviceCache();

if (this.argumentResolvers == null) {

List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();

this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);

}

if (this.initBinderArgumentResolvers == null) {

List<HandlerMethodArgumentResolver> resolvers = getDefaultInitBinderArgumentResolvers();

this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);

}

if (this.returnValueHandlers == null) {

List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers();

this.returnValueHandlers = new HandlerMethodReturnValueHandlerCompos

ull) {

L

andlers(handle

ull) {

L

}

ull) {

L

private void initControllerAdviceCache() {

...

if (logger.isInfoEnabled()) {

logger.info("Looking for @ControllerAdvice: " + getApplicationContext());

}

List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());

AnnotationAwareOrderComparator.sort(beans);

List<Object> requestResponseBodyAdviceBeans = new ArrayList<Object>();

for (ControllerAdviceBean bean : beans) {

...

if (ResponseBodyAdvice.class.isAssignableFrom(bean.getBeanType())) {

requestRespon

(beans);

List<Object> requestRe

ns);

List<Object> requestResponseBodyAdviceBean

sponseBodyAdviceBean

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@ControllerAdvice

@Response

stResponseBodyAdviceBeans.add(bean);

stResponseBodyAdviceBeans.add(bean);

}

}

ceBeans.add(bean);

}

}

}

}

}

通过 ControllerAdviceBean 静态方法扫描

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@ControllerAdvice

@ResponseBo

@ControllerAdvice

@ResponseBody

public @interfa

eBody

public @interface RestControllerAd

ce RestControllerAd

if (messageConverter instanceof GenericHttpMessageConverter) {

if (((GenericHttpMessageConverter) messageConverter).canWrite(

declaredType, valueType, selectedMediaType)) {

outputValue = (T) getAdvice().beforeBodyWrite(outputValue, returnType, selectedMediaType,

(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),

inputMessage, outputMessage);

...

return;

}

}

nericHttpMessageConve

pro

{

outputValue = (T) getAdvice().bef

{

outputValue = (T) getAdvice().beforeBodyWrite(outputValue, retur

) getAdvice().beforeBodyWrite(outputValue, retur

class RequestResponseBodyAdviceChain implements RequestBodyAdvice, ResponseBodyAdvice<Object> {

@Override

public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType contentType,

Class<? extends HttpMessageConverter<?>> converterType,

ServerHttpRequest request, ServerHttpResponse response) {

return processBody(body, returnType, contentType, converterType, request, response);

}

@SuppressWarnings("unchecked")

private <T> Object processBody(Object body, MethodParameter returnType, MediaType contentType,

Class<? extends HttpMessageConverter<?>> converterType,

ServerHttpRequest request, ServerHttpResponse response) {

for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {

if (advice.supports(returnType, converterType)) {

body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,

e,

ServerHttpRequest request, ServerHttpResponse response) {

for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {

if (advice.supports(returnType, converterType)) {

body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,

contentType, converterType, reques

body, returnType,

contentType, converterType, request, response);

}

}

re

verterType, request, response);

}

}

return body;

}

}

);

}

}

return body;

}

}

}

@Override

public void handleReturnValue(Object returnValue, MethodParameter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

HandlerMethodReturnValueHandler handler = selectHandler(returnValue, returnType);

if (handler == null) {

throw new IllegalArgumentException("Unknown return value type: " + returnType.g

Value, MethodParameter returnType,

ModelAndViewContainer mavContaine

meter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest)

iner, NativeWebRequest webRequest) throws Exception {

t) throws Exception {

HandlerMethodReturnVal

HandlerMethodReturnVal

@Override

public boolean supportsParameter(MethodParameter parameter

;

}

handler.handleReturnValue(returnValue, retur

;

}

handler.handleReturnValue(retu

;

}

handler.handleReturnValue(returnValue, returnType, mavContainer, webRequ

ue(returnValue, returnType, mavContainer, webRequ

@Override

public void handleReturnValue(Object returnValue, MethodParameter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

...

if (responseEntity instanceof ResponseEntity) {

int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();

outputMessage.getServletResponse().setStatus(returnStatus);

if (returnStatus == 200) {

if (SAFE_METHODS.contains(inputMessage.getMethod())

&& isResourceNotModified(inputMessage, outputMessage)) {

// Ensure headers are flushed, no body should be written.

outputMessage.flush();

// Skip call to converters, as they may update the body.

return;

}

}

}

// Try even with null body. ResponseBodyAdvice could get involved.

writeWithMessageConverters(responseEntity.getBody()

od())

&& isResourceNotModified(inputMessage, outputMessage)) {

// Ensure headers are flushed, no body should be written.

outputMessage.flush();

// Skip call to converters, as they may update the body.

return;

}

}

}

// Try even with null body. ResponseBodyAdvice could get involved.

writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

// Ens

ty.getBody(), returnType, inputMessage, outputMessage);

// Ensure headers are flushed even i

);

// Ensure headers are flushed even if no body was written.

outp

ed even if no body was written.

outputMessage.flush();

}

.

outputMessage.flush();

}

该方法提取出 responseEntity.getBody(),并传递个 MessageConverter,然后再继续调用 beforeBodyWrite 方法,这才是真相!!!

这是 RESTful API 正常返回内容的情况

以上是关于SpringBoot定义优雅全局统一Restful API 响应框架三的主要内容,如果未能解决你的问题,请参考以下文章

每天用SpringBoot,还不懂RESTful API返回统一数据格式是怎么实现的?

spring boot 2 全局统一返回RESTful风格数据统一异常处理

SpringBoot:如何优雅地处理全局异常?

企业级 SpringBoot 教程 springboot集成swagger2,构建优雅的Restful API

SpringBoot/SpringMVC Restful接口全局异常处理

springboot集成swagger2,构建优雅的Restful API