├── src └── main │ ├── resources │ ├── i18n │ │ ├── graceful-response_zh_CN.properties │ │ └── graceful-response_en.properties │ ├── validation-code.http │ ├── static │ │ └── view.html │ └── application.yaml │ └── java │ └── com │ └── feiniaojin │ └── gracefuresponse │ └── example │ ├── dto │ ├── Issue67Child.java │ ├── Result.java │ ├── Issue67Parent.java │ ├── ClassValidateCode.java │ ├── CustomValidationUserQuery.java │ ├── InnerDto.java │ ├── ExtendProperties.java │ ├── UserInfoView.java │ ├── UserInfoCommand.java │ ├── UserInfoQuery.java │ ├── MethodDTO.java │ ├── PageBeanX.java │ └── PropertyListMethodDTO.java │ ├── exceptions │ ├── MapperDemoException.java │ ├── I18nSampleException.java │ ├── NotFoundException.java │ ├── AliasDemoException.java │ ├── ExampleExceptions.java │ ├── ExcludeException.java │ ├── outer │ │ ├── OuterException.java │ │ ├── BbOuterException.java │ │ └── AliasOuterException.java │ ├── RatException.java │ ├── ExceptionEnum.java │ ├── excludep │ │ └── PackageExcludeException.java │ └── ReplaceMsgException.java │ ├── service │ ├── ExampleService.java │ └── impl │ │ └── ExampleServiceImpl.java │ ├── ExampleApplication.java │ ├── controller │ ├── I18nController.java │ ├── ExceptionEnumController.java │ ├── Issue67Controller.java │ ├── exclude │ │ └── ExcludeController.java │ ├── Exclude1Controller.java │ ├── AlisaController.java │ ├── ExceptionMapperController.java │ ├── GracefulResponseController.java │ ├── ValidationController.java │ └── QuickStartController.java │ ├── validation │ ├── UserIdValidator.java │ └── UserId.java │ ├── config │ ├── GracefulResponseConfig.java │ ├── CustomResponseImpl.java │ ├── ExampleConfig.java │ └── ApiDocsOperationCustomizer.java │ └── ext │ ├── RejectExceptionHandler.java │ ├── IntCodeResponseBodyAdvice.java │ └── IntCodeResponseImpl.java ├── README.md ├── graceful-response-example.iml ├── .gitignore ├── pom.xml └── LICENSE /src/main/resources/i18n/graceful-response_zh_CN.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Graceful Response 使用案例 2 | 3 | 本案例基于Spring Boot 3版本。 4 | -------------------------------------------------------------------------------- /src/main/resources/i18n/graceful-response_en.properties: -------------------------------------------------------------------------------- 1 | 999=EnglishErrorMessage 2 | -------------------------------------------------------------------------------- /src/main/resources/validation-code.http: -------------------------------------------------------------------------------- 1 | ### 2 | POST http://127.0.0.1:9090/example/classValidateCode 3 | Content-Type: application/json 4 | 5 | { 6 | "id": null 7 | } 8 | 9 | ### 10 | -------------------------------------------------------------------------------- /src/main/resources/static/view.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 |

Hello!

9 | 10 | 11 | -------------------------------------------------------------------------------- /graceful-response-example.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/Issue67Child.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Issue67Child extends Issue67Parent{ 7 | private String childName; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/Result.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class Result { 9 | private Integer resultCode; 10 | private String resultMsg; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/Issue67Parent.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import jakarta.validation.constraints.NotBlank; 4 | import lombok.Data; 5 | 6 | @Data 7 | public class Issue67Parent { 8 | 9 | @NotBlank(message = "编码不能为空") 10 | private String code; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/MapperDemoException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | 4 | import com.feiniaojin.gracefulresponse.api.ExceptionMapper; 5 | 6 | @ExceptionMapper(code = "1001",msg = "自定义异常信息") 7 | public class MapperDemoException extends RuntimeException{ 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/I18nSampleException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ExceptionMapper; 4 | 5 | /** 6 | * @author qinyujie 7 | */ 8 | @ExceptionMapper(code = "999", msg = "中文的异常信息") 9 | public class I18nSampleException extends RuntimeException { 10 | } 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | .idea 26 | target 27 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/ClassValidateCode.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ValidationStatusCode; 4 | import jakarta.validation.constraints.NotNull; 5 | import lombok.Data; 6 | 7 | @ValidationStatusCode(code = "1500") 8 | @Data 9 | public class ClassValidateCode { 10 | @NotNull 11 | private Long id; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ExceptionAliasFor; 4 | import org.springframework.web.servlet.NoHandlerFoundException; 5 | 6 | @ExceptionAliasFor(code = "1404", msg = "not found", aliasFor = NoHandlerFoundException.class) 7 | public class NotFoundException extends RuntimeException { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/CustomValidationUserQuery.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import com.feiniaojin.gracefuresponse.example.validation.UserId; 4 | import lombok.Data; 5 | 6 | @Data 7 | public class CustomValidationUserQuery { 8 | 9 | /** 10 | * 自定义的校验注解 11 | */ 12 | @UserId(message = "用户账号不合法") 13 | private String userId; 14 | 15 | private String username; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/InnerDto.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ValidationStatusCode; 4 | import jakarta.validation.constraints.NotNull; 5 | import lombok.Data; 6 | 7 | 8 | @Data 9 | public class InnerDto { 10 | @NotNull(message = "innerProperty is null !") 11 | @ValidationStatusCode(code = "522") 12 | private String innerProperty; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/AliasDemoException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ExceptionAliasFor; 4 | import org.springframework.web.client.HttpClientErrorException; 5 | 6 | @ExceptionAliasFor(code = "1404",msg = "自定义异常信息", 7 | aliasFor = HttpClientErrorException.NotFound.class) 8 | public class AliasDemoException extends RuntimeException{ 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/ExtendProperties.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ValidationStatusCode; 4 | import jakarta.validation.constraints.NotNull; 5 | import lombok.Data; 6 | 7 | @Data 8 | @ValidationStatusCode(code = "456") 9 | public class ExtendProperties { 10 | @NotNull(message = "扩展属性property1不能为空") 11 | // @ValidationStatusCode(code = "123") 12 | private String property1; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/service/ExampleService.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.service; 2 | 3 | /** 4 | * 测试Service接口. 5 | * 6 | * @author qinyujie 7 | */ 8 | public interface ExampleService { 9 | /** 10 | * 测试产生非受检异常的情形,即抛出运行时异常. 11 | */ 12 | void testUnCheckedException(); 13 | 14 | /** 15 | * 测试抛出受检异常的情况. 16 | * 17 | * @throws Exception 抛出受检异常 18 | */ 19 | void testCheckedException() throws Exception; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/ExampleApplication.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example; 2 | 3 | import com.feiniaojin.gracefulresponse.EnableGracefulResponse; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.data.web.config.EnableSpringDataWebSupport; 7 | 8 | @EnableGracefulResponse 9 | @SpringBootApplication 10 | public class ExampleApplication { 11 | public static void main(String[] args) { 12 | SpringApplication.run(ExampleApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/I18nController.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefuresponse.example.exceptions.I18nSampleException; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | @RequestMapping("/i18n") 10 | public class I18nController { 11 | 12 | @GetMapping("/test0") 13 | public void test0() { 14 | throw new I18nSampleException(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/ExampleExceptions.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | 4 | import com.feiniaojin.gracefulresponse.api.ExceptionMapper; 5 | 6 | /** 7 | * 测试用例的异常,包括运行时异常和受检异常. 8 | * 9 | * @author qinyujie 10 | * @version 0.1 11 | */ 12 | public class ExampleExceptions { 13 | 14 | @ExceptionMapper(code = "1024", msg = "UnCheckedException") 15 | public static class UnCheckedException extends RuntimeException { 16 | 17 | } 18 | 19 | @ExceptionMapper(code = "2048", msg = "CheckedException") 20 | public static class CheckedException extends Exception { 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/UserInfoView.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import io.swagger.v3.oas.annotations.media.Schema; 4 | import io.swagger.v3.oas.annotations.tags.Tag; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | 8 | /** 9 | * ResponseDto. 10 | * 11 | * @author feiniaojin 12 | * @date 2020/05/14 13 | */ 14 | @Data 15 | @Builder 16 | @Tag(name = "用户信息", description = "用户信息视图对象") 17 | public class UserInfoView { 18 | 19 | @Schema(name = "id", description = "用户id", type = "long") 20 | private Long id; 21 | 22 | @Schema(description = "用户名", type = "string") 23 | private String name; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/service/impl/ExampleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.service.impl; 2 | 3 | import com.feiniaojin.gracefuresponse.example.exceptions.ExampleExceptions; 4 | import com.feiniaojin.gracefuresponse.example.service.ExampleService; 5 | import org.springframework.stereotype.Service; 6 | 7 | @Service 8 | public class ExampleServiceImpl implements ExampleService { 9 | @Override 10 | public void testUnCheckedException() { 11 | throw new ExampleExceptions.UnCheckedException(); 12 | } 13 | 14 | @Override 15 | public void testCheckedException() throws Exception { 16 | throw new ExampleExceptions.CheckedException(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/UserInfoCommand.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ValidationStatusCode; 4 | import jakarta.validation.Valid; 5 | import jakarta.validation.constraints.NotNull; 6 | import lombok.Data; 7 | import org.hibernate.validator.constraints.Length; 8 | 9 | 10 | @Data 11 | public class UserInfoCommand { 12 | @NotNull(message = "userId is null !") 13 | private Long userId; 14 | 15 | @NotNull(message = "userName is null !") 16 | @Length(min = 6, max = 12) 17 | @ValidationStatusCode(code = "520") 18 | private String userName; 19 | 20 | @NotNull(message = "extendProperties is null !") 21 | @Valid 22 | private ExtendProperties extendProperties; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/ExceptionEnumController.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefulresponse.GracefulResponse; 4 | import com.feiniaojin.gracefuresponse.example.exceptions.ExceptionEnum; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * 异常枚举的使用示例 11 | * 12 | * @author qinyujie 13 | */ 14 | @RestController 15 | @RequestMapping("/enum") 16 | public class ExceptionEnumController { 17 | 18 | @GetMapping("/test0") 19 | public void test0() { 20 | GracefulResponse.raiseException(ExceptionEnum.CUSTOM_EXCEPTION); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/ExcludeException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | /** 4 | * 用来测试异常放行的场景 5 | */ 6 | public class ExcludeException extends RuntimeException { 7 | public ExcludeException() { 8 | } 9 | 10 | public ExcludeException(String message) { 11 | super(message); 12 | } 13 | 14 | public ExcludeException(String message, Throwable cause) { 15 | super(message, cause); 16 | } 17 | 18 | public ExcludeException(Throwable cause) { 19 | super(cause); 20 | } 21 | 22 | public ExcludeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 23 | super(message, cause, enableSuppression, writableStackTrace); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/validation/UserIdValidator.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.validation; 2 | 3 | import jakarta.validation.ConstraintValidator; 4 | import jakarta.validation.ConstraintValidatorContext; 5 | import org.apache.commons.lang3.StringUtils; 6 | 7 | public class UserIdValidator implements ConstraintValidator { 8 | 9 | private static final int LENGTH = 10; 10 | 11 | private static final String PRE_FIX = "U"; 12 | 13 | @Override 14 | public boolean isValid(String s, ConstraintValidatorContext context) { 15 | 16 | if (StringUtils.isBlank(s)) { 17 | return false; 18 | } 19 | if (s.length() != LENGTH) { 20 | return false; 21 | } 22 | return s.startsWith(PRE_FIX); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/outer/OuterException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions.outer; 2 | 3 | /** 4 | * 模拟外部异常 5 | * 6 | * @author qinyujie 7 | */ 8 | public class OuterException extends RuntimeException { 9 | 10 | public OuterException() { 11 | } 12 | 13 | public OuterException(String message) { 14 | super(message); 15 | } 16 | 17 | public OuterException(String message, Throwable cause) { 18 | super(message, cause); 19 | } 20 | 21 | public OuterException(Throwable cause) { 22 | super(cause); 23 | } 24 | 25 | public OuterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 26 | super(message, cause, enableSuppression, writableStackTrace); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/outer/BbOuterException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions.outer; 2 | 3 | /** 4 | * 模拟外部异常 5 | * 6 | * @author qinyujie 7 | */ 8 | public class BbOuterException extends RuntimeException { 9 | 10 | public BbOuterException() { 11 | super(); 12 | } 13 | 14 | public BbOuterException(String message) { 15 | super(message); 16 | } 17 | 18 | public BbOuterException(String message, Throwable cause) { 19 | super(message, cause); 20 | } 21 | 22 | public BbOuterException(Throwable cause) { 23 | super(cause); 24 | } 25 | 26 | protected BbOuterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 27 | super(message, cause, enableSuppression, writableStackTrace); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/RatException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ExceptionMapper; 4 | 5 | @ExceptionMapper(code = "1007", msg = "有内鬼,终止交易", msgReplaceable = true) 6 | public class RatException extends RuntimeException { 7 | public RatException() { 8 | } 9 | 10 | public RatException(String message) { 11 | super(message); 12 | } 13 | 14 | public RatException(String message, Throwable cause) { 15 | super(message, cause); 16 | } 17 | 18 | public RatException(Throwable cause) { 19 | super(cause); 20 | } 21 | 22 | public RatException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 23 | super(message, cause, enableSuppression, writableStackTrace); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/ExceptionEnum.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | import com.feiniaojin.gracefulresponse.data.ResponseStatus; 4 | 5 | /** 6 | * 异常枚举 7 | * 8 | * @author qinyujie 9 | */ 10 | public enum ExceptionEnum implements ResponseStatus { 11 | 12 | /** 13 | * 测试自定义的错误码 14 | */ 15 | CUSTOM_EXCEPTION("520", "520自定义的异常"); 16 | /** 17 | * 错误码 18 | */ 19 | private final String code; 20 | /** 21 | * 异常信息 22 | */ 23 | private final String msg; 24 | 25 | ExceptionEnum(String code, String msg) { 26 | this.code = code; 27 | this.msg = msg; 28 | } 29 | 30 | @Override 31 | public String getCode() { 32 | return code; 33 | } 34 | 35 | @Override 36 | public String getMsg() { 37 | return msg; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/validation/UserId.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.validation; 2 | 3 | import jakarta.validation.Constraint; 4 | import jakarta.validation.Payload; 5 | import jakarta.validation.ReportAsSingleViolation; 6 | 7 | import java.lang.annotation.Documented; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.Target; 10 | 11 | import static java.lang.annotation.ElementType.FIELD; 12 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 13 | 14 | /** 15 | * 用户ID的校验 16 | */ 17 | @Target({FIELD}) 18 | @Retention(RUNTIME) 19 | @Constraint(validatedBy = UserIdValidator.class) 20 | @Documented 21 | @ReportAsSingleViolation 22 | public @interface UserId { 23 | 24 | String message() default ""; 25 | 26 | Class[] groups() default {}; 27 | 28 | Class[] payload() default {}; 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/excludep/PackageExcludeException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions.excludep; 2 | 3 | /** 4 | * 根据包路径进行放行 5 | * 6 | * @author qinyujie 7 | */ 8 | public class PackageExcludeException extends RuntimeException { 9 | 10 | public PackageExcludeException() { 11 | } 12 | 13 | public PackageExcludeException(String message) { 14 | super(message); 15 | } 16 | 17 | public PackageExcludeException(String message, Throwable cause) { 18 | super(message, cause); 19 | } 20 | 21 | public PackageExcludeException(Throwable cause) { 22 | super(cause); 23 | } 24 | 25 | public PackageExcludeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 26 | super(message, cause, enableSuppression, writableStackTrace); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/ReplaceMsgException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ExceptionMapper; 4 | 5 | @ExceptionMapper(code = "1222", msg = "error", msgReplaceable = true) 6 | public class ReplaceMsgException extends RuntimeException { 7 | public ReplaceMsgException() { 8 | } 9 | 10 | public ReplaceMsgException(String message) { 11 | super(message); 12 | } 13 | 14 | public ReplaceMsgException(String message, Throwable cause) { 15 | super(message, cause); 16 | } 17 | 18 | public ReplaceMsgException(Throwable cause) { 19 | super(cause); 20 | } 21 | 22 | public ReplaceMsgException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 23 | super(message, cause, enableSuppression, writableStackTrace); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/Issue67Controller.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefuresponse.example.dto.Issue67Child; 4 | import com.feiniaojin.gracefuresponse.example.dto.Issue67Parent; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.validation.annotation.Validated; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | 12 | @RequestMapping("/issue67") 13 | @RestController 14 | @Slf4j 15 | public class Issue67Controller { 16 | 17 | 18 | @RequestMapping("/command") 19 | public void command(@Validated @RequestBody Issue67Child child) { 20 | log.info("正常进行校验"); 21 | } 22 | 23 | @RequestMapping("/parent") 24 | public void parent(@Validated @RequestBody Issue67Parent parent) { 25 | log.info("正常进行校验"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/exceptions/outer/AliasOuterException.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.exceptions.outer; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ExceptionAliasFor; 4 | 5 | /** 6 | * 模拟外部异常 7 | * 8 | * @author qinyujie 9 | */ 10 | @ExceptionAliasFor(aliasFor = BbOuterException.class, code = "520", msg = "123", httpStatusCode = 500) 11 | public class AliasOuterException extends RuntimeException { 12 | 13 | public AliasOuterException() { 14 | } 15 | 16 | public AliasOuterException(String message) { 17 | super(message); 18 | } 19 | 20 | public AliasOuterException(String message, Throwable cause) { 21 | super(message, cause); 22 | } 23 | 24 | public AliasOuterException(Throwable cause) { 25 | super(cause); 26 | } 27 | 28 | public AliasOuterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 29 | super(message, cause, enableSuppression, writableStackTrace); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/exclude/ExcludeController.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller.exclude; 2 | 3 | import com.feiniaojin.gracefuresponse.example.dto.UserInfoView; 4 | import io.swagger.v3.oas.annotations.tags.Tag; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * @author qinyujie 14 | */ 15 | @RestController 16 | @RequestMapping("/exclude") 17 | @Tag(name = "根据Controller包路径放行的案例接口", description = "一些用来作为示例的基础接口") 18 | public class ExcludeController { 19 | 20 | @GetMapping("/test") 21 | public Map test() { 22 | Map result = new HashMap<>(); 23 | result.put("key", "value"); 24 | return result; 25 | } 26 | 27 | @GetMapping("/test1") 28 | public UserInfoView test1(){ 29 | return UserInfoView.builder().build(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/UserInfoQuery.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ValidationStatusCode; 4 | import io.swagger.v3.oas.annotations.media.Schema; 5 | import io.swagger.v3.oas.annotations.tags.Tag; 6 | import jakarta.validation.constraints.NotNull; 7 | import lombok.Data; 8 | import org.hibernate.validator.constraints.Length; 9 | import org.hibernate.validator.constraints.Range; 10 | 11 | /** 12 | * 请求的DTO. 13 | * 14 | * @author qinyujie 15 | */ 16 | @Data 17 | @Schema(name = "UserInfoQuery", description = "用户信息Query查询对象") 18 | public class UserInfoQuery { 19 | 20 | @NotNull(message = "userId is null !") 21 | @Schema(name = "userId", description = "用户Id",type = "long") 22 | private Long userId; 23 | 24 | @NotNull(message = "userName is null !") 25 | @Length(min = 6, max = 12) 26 | @ValidationStatusCode(code = "520") 27 | @Schema(description = "用户名") 28 | private String userName; 29 | 30 | @NotNull(message = "age is null !") 31 | @Range(min = 18, max = 50,message = "年龄必须在18~50之间") 32 | private Integer age; 33 | 34 | @NotNull 35 | private Integer gender; 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/config/GracefulResponseConfig.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.config; 2 | 3 | import com.feiniaojin.gracefulresponse.AbstractExceptionAliasRegisterConfig; 4 | import com.feiniaojin.gracefulresponse.ExceptionAliasRegister; 5 | import com.feiniaojin.gracefuresponse.example.exceptions.AliasDemoException; 6 | import com.feiniaojin.gracefuresponse.example.exceptions.NotFoundException; 7 | import com.feiniaojin.gracefuresponse.example.exceptions.outer.AliasOuterException; 8 | import com.feiniaojin.gracefuresponse.example.ext.IntCodeResponseBodyAdvice; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | @Configuration 13 | public class GracefulResponseConfig extends AbstractExceptionAliasRegisterConfig { 14 | 15 | @Override 16 | protected void registerAlias(ExceptionAliasRegister aliasRegister) { 17 | aliasRegister.doRegisterExceptionAlias(NotFoundException.class); 18 | aliasRegister.doRegisterExceptionAlias(AliasOuterException.class); 19 | } 20 | 21 | @Bean 22 | public IntCodeResponseBodyAdvice intCodeResponseBodyAdvice() { 23 | return new IntCodeResponseBodyAdvice(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/MethodDTO.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.feiniaojin.gracefulresponse.api.ValidationStatusCode; 6 | import jakarta.validation.Valid; 7 | import jakarta.validation.constraints.NotNull; 8 | import lombok.Data; 9 | import org.hibernate.validator.constraints.Length; 10 | 11 | 12 | @Data 13 | public class MethodDTO { 14 | 15 | @NotNull(message = "uid is null !") 16 | @Length(min = 6, max = 12) 17 | @ValidationStatusCode(code = "520") 18 | private String uid; 19 | 20 | @NotNull(message = "innerDTO is null") 21 | // @ValidationStatusCode(code = "521") 22 | @Valid 23 | private InnerDto innerDto; 24 | 25 | public static void main(String[] args) throws JsonProcessingException { 26 | String input = "{\n" + 27 | " \"uid\": \"123456\",\n" + 28 | " \"inner\": {\n" + 29 | " \"innerProperty\": null\n" + 30 | " }\n" + 31 | "}"; 32 | 33 | ObjectMapper mapper = new ObjectMapper(); 34 | MethodDTO methodDTO = mapper.readValue(input, MethodDTO.class); 35 | System.out.println(methodDTO); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/ext/RejectExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.ext; 2 | 3 | import com.feiniaojin.gracefuresponse.example.exceptions.ExcludeException; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.core.annotation.Order; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.web.bind.annotation.ControllerAdvice; 9 | import org.springframework.web.bind.annotation.ExceptionHandler; 10 | import org.springframework.web.bind.annotation.ResponseBody; 11 | import org.springframework.web.bind.annotation.ResponseStatus; 12 | 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | @ControllerAdvice 17 | @Order(300) 18 | public class RejectExceptionHandler { 19 | 20 | private Logger logger = LoggerFactory.getLogger(RejectExceptionHandler.class); 21 | 22 | 23 | /** 24 | * 通过ResponseStatus指定最终的状态码 25 | * @param throwable 26 | * @return 27 | */ 28 | @ExceptionHandler(value = ExcludeException.class) 29 | @ResponseBody 30 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 31 | public Map exceptionHandler(Throwable throwable) { 32 | logger.info("进入外部的RejectExceptionHandler处理逻辑"); 33 | Map result = new HashMap<>(); 34 | result.put("grace", "response"); 35 | return result; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/PageBeanX.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import io.swagger.v3.oas.annotations.media.Schema; 4 | import io.swagger.v3.oas.annotations.tags.Tag; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author Yujie 10 | * @version 0.1 11 | */ 12 | @Tag(name = "分页容器", description = "分页容器") 13 | public class PageBeanX { 14 | 15 | @Schema(description = "每页数据大小") 16 | private Integer pageSize; 17 | @Schema(description = "总数据量") 18 | private Integer total; 19 | @Schema(description = "当前页码") 20 | private Integer page; 21 | @Schema(description = "数据列表") 22 | private List list; 23 | 24 | public Integer getPageSize() { 25 | return pageSize; 26 | } 27 | 28 | public void setPageSize(Integer pageSize) { 29 | this.pageSize = pageSize; 30 | } 31 | 32 | public Integer getTotal() { 33 | return total; 34 | } 35 | 36 | public void setTotal(Integer total) { 37 | this.total = total; 38 | } 39 | 40 | public Integer getPage() { 41 | return page; 42 | } 43 | 44 | public void setPage(Integer page) { 45 | this.page = page; 46 | } 47 | 48 | public List getList() { 49 | return list; 50 | } 51 | 52 | public void setList(List list) { 53 | this.list = list; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/dto/PropertyListMethodDTO.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.dto; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.feiniaojin.gracefulresponse.api.ValidationStatusCode; 6 | import jakarta.validation.Valid; 7 | import jakarta.validation.constraints.NotNull; 8 | import lombok.Data; 9 | import org.hibernate.validator.constraints.Length; 10 | 11 | import java.util.List; 12 | 13 | 14 | @Data 15 | public class PropertyListMethodDTO { 16 | 17 | @NotNull(message = "uid is null !") 18 | @Length(min = 6, max = 12) 19 | @ValidationStatusCode(code = "520") 20 | private String uid; 21 | 22 | @NotNull(message = "innerDTO is null") 23 | // @ValidationStatusCode(code = "521") 24 | @Valid 25 | private List innerDto; 26 | 27 | public static void main(String[] args) throws JsonProcessingException { 28 | String input = "{\n" + 29 | " \"uid\": \"123456\",\n" + 30 | " \"inner\": {\n" + 31 | " \"innerProperty\": null\n" + 32 | " }\n" + 33 | "}"; 34 | 35 | ObjectMapper mapper = new ObjectMapper(); 36 | PropertyListMethodDTO methodDTO = mapper.readValue(input, PropertyListMethodDTO.class); 37 | System.out.println(methodDTO); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/Exclude1Controller.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefuresponse.example.dto.Result; 4 | import com.feiniaojin.gracefuresponse.example.exceptions.ExcludeException; 5 | import com.feiniaojin.gracefuresponse.example.exceptions.excludep.PackageExcludeException; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("/exclude1") 13 | @Slf4j 14 | public class Exclude1Controller { 15 | 16 | @GetMapping("/test0") 17 | public Result test0() { 18 | log.info("Exclude1Controller#test0"); 19 | return Result.builder().resultCode(100).resultMsg("100msg").build(); 20 | } 21 | 22 | /** 23 | * 放行某个具体的异常 24 | * 25 | * @return 26 | */ 27 | @GetMapping("/test1") 28 | public Result test1() { 29 | log.info("Exclude1Controller#test1"); 30 | throw new ExcludeException("放行异常"); 31 | } 32 | 33 | /** 34 | * 根据某个包路径放行异常 35 | * 36 | * @return 37 | */ 38 | @GetMapping("/test2") 39 | public Result test2() { 40 | log.info("Exclude1Controller#test2"); 41 | throw new PackageExcludeException("放行异常"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/ext/IntCodeResponseBodyAdvice.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.ext; 2 | 3 | import com.feiniaojin.gracefulresponse.data.Response; 4 | import org.springframework.core.MethodParameter; 5 | import org.springframework.core.annotation.Order; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.http.converter.HttpMessageConverter; 8 | import org.springframework.http.server.ServerHttpRequest; 9 | import org.springframework.http.server.ServerHttpResponse; 10 | import org.springframework.web.bind.annotation.ControllerAdvice; 11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 12 | 13 | /** 14 | * 将字符串类型的code适配为int类型 15 | * 16 | * @author qinyujie 17 | */ 18 | //@ControllerAdvice 19 | @Order(2008) 20 | public class IntCodeResponseBodyAdvice implements ResponseBodyAdvice { 21 | 22 | @Override 23 | public boolean supports(MethodParameter returnType, Class> converterType) { 24 | return true; 25 | } 26 | 27 | @Override 28 | public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { 29 | if (body instanceof Response res) { 30 | return new IntCodeResponseImpl(res); 31 | } 32 | return body; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/ext/IntCodeResponseImpl.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.ext; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.feiniaojin.gracefulresponse.data.Response; 5 | import com.feiniaojin.gracefulresponse.data.ResponseStatus; 6 | 7 | /** 8 | * 将字符串的code适配为int 9 | * 10 | * @author qinyujie 11 | */ 12 | public class IntCodeResponseImpl implements Response { 13 | 14 | private final Response response; 15 | 16 | public IntCodeResponseImpl(Response response) { 17 | this.response = response; 18 | } 19 | 20 | @Override 21 | public void setStatus(ResponseStatus statusLine) { 22 | this.response.setStatus(statusLine); 23 | } 24 | 25 | @Override 26 | @JsonIgnore 27 | public ResponseStatus getStatus() { 28 | return this.response.getStatus(); 29 | } 30 | 31 | @Override 32 | public void setPayload(Object payload) { 33 | this.response.setPayload(payload); 34 | } 35 | 36 | @Override 37 | @JsonIgnore 38 | public Object getPayload() { 39 | return this.response.getPayload(); 40 | } 41 | 42 | public Integer getCode() { 43 | return Integer.valueOf(this.response.getStatus().getCode()); 44 | } 45 | 46 | public String getMsg() { 47 | return this.response.getStatus().getMsg(); 48 | } 49 | 50 | public Object getData() { 51 | return this.response.getPayload(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/AlisaController.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefuresponse.example.dto.UserInfoView; 4 | import com.feiniaojin.gracefuresponse.example.exceptions.outer.BbOuterException; 5 | import com.feiniaojin.gracefuresponse.example.exceptions.outer.OuterException; 6 | import io.swagger.v3.oas.annotations.media.Content; 7 | import io.swagger.v3.oas.annotations.media.Schema; 8 | import io.swagger.v3.oas.annotations.responses.ApiResponse; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | /** 14 | * 异常别名的用法示例 15 | * 16 | * @author qinyujie 17 | */ 18 | @RestController 19 | @RequestMapping("/alias") 20 | public class AlisaController { 21 | 22 | /** 23 | * 模拟抛出一个外部异常的场景 24 | */ 25 | @GetMapping("/test0") 26 | @ApiResponse(responseCode = "401", description = "查询成功", 27 | content = @Content(schema = @Schema(implementation = UserInfoView.class))) 28 | public void test0() { 29 | throw new OuterException(); 30 | } 31 | 32 | /** 33 | * 模拟抛出一个外部异常的场景 34 | */ 35 | @GetMapping("/test1") 36 | @ApiResponse(responseCode = "500", description = "查询成功", 37 | content = @Content(schema = @Schema(implementation = UserInfoView.class))) 38 | public void test1() { 39 | throw new BbOuterException(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9168 3 | springdoc: 4 | swagger-ui: 5 | path: /swagger-ui.html 6 | graceful-response: 7 | print-exception-in-global-advice: true 8 | default-error-msg: fail 9 | default-error-code: 500 10 | default-success-code: 200 11 | default-success-msg: success 12 | response-style: 1 13 | exclude-packages: 14 | - com.feiniaojin.*.controller.exclude 15 | - springfox.** 16 | # response-class-full-name: com.feiniaojin.gracefuresponse.example.config.CustomResponseImpl 17 | origin-exception-using-detail-message: false 18 | default-validate-error-code: 999 19 | exclude-urls: 20 | # - /**/ex/** 21 | - /**/api-docs/** 22 | # - /**/error/** 23 | i18n: true 24 | exclude-return-types: 25 | - com.feiniaojin.gracefuresponse.example.dto.Result 26 | exclude-exception-types: 27 | - com.feiniaojin.gracefuresponse.example.exceptions.ExcludeException 28 | exclude-exception-packages: 29 | - "*excludep*" 30 | exception-alias-config-map: 31 | "[com.feiniaojin.gracefuresponse.example.exceptions.outer.OuterException]": 32 | code: 5200 33 | msg: "通过配置文件配置OuterException的提示" 34 | httpStatusCode: 401 35 | 36 | # json-http-message-converter: com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter 37 | spring: 38 | mvc: 39 | throw-exception-if-no-handler-found: true 40 | static-path-pattern: "*.html" 41 | view: 42 | suffix: .html 43 | prefix: / 44 | web: 45 | resources: 46 | add-mappings: false 47 | 48 | logging: 49 | level: 50 | com.feiniaojin: DEBUG 51 | 52 | knife4j: 53 | enable: true 54 | setting: 55 | language: zh_cn 56 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/config/CustomResponseImpl.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.feiniaojin.gracefulresponse.data.Response; 5 | import com.feiniaojin.gracefulresponse.data.ResponseStatus; 6 | 7 | import java.util.Collections; 8 | 9 | public class CustomResponseImpl implements Response { 10 | 11 | private String code; 12 | 13 | private Long timestamp = System.currentTimeMillis(); 14 | 15 | private String msg; 16 | 17 | private Object data = Collections.EMPTY_MAP; 18 | 19 | @Override 20 | public void setStatus(ResponseStatus statusLine) { 21 | this.code = statusLine.getCode(); 22 | this.msg = statusLine.getMsg(); 23 | } 24 | 25 | @Override 26 | @JsonIgnore 27 | public ResponseStatus getStatus() { 28 | return null; 29 | } 30 | 31 | @Override 32 | public void setPayload(Object payload) { 33 | this.data = payload; 34 | } 35 | 36 | @Override 37 | @JsonIgnore 38 | public Object getPayload() { 39 | return null; 40 | } 41 | 42 | public String getCode() { 43 | return code; 44 | } 45 | 46 | public void setCode(String code) { 47 | this.code = code; 48 | } 49 | 50 | public String getMsg() { 51 | return msg; 52 | } 53 | 54 | public void setMsg(String msg) { 55 | this.msg = msg; 56 | } 57 | 58 | public Object getData() { 59 | return data; 60 | } 61 | 62 | public void setData(Object data) { 63 | this.data = data; 64 | } 65 | 66 | public Long getTimestamp() { 67 | return timestamp; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/ExceptionMapperController.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefuresponse.example.dto.UserInfoView; 4 | import com.feiniaojin.gracefuresponse.example.exceptions.ReplaceMsgException; 5 | import com.feiniaojin.gracefuresponse.example.service.ExampleService; 6 | import io.swagger.v3.oas.annotations.tags.Tag; 7 | import jakarta.annotation.Resource; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.validation.annotation.Validated; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | 15 | /** 16 | * class {@code ExampleController} 使用案例的Controller. 17 | * 18 | * @author qinyujie 19 | */ 20 | @RestController 21 | @RequestMapping("/em") 22 | @Slf4j 23 | @Validated 24 | @Tag(name = "@ExceptionMapper注解案例接口", description = "演示@ExceptionMapper注解的使用") 25 | public class ExceptionMapperController { 26 | 27 | @Resource 28 | private ExampleService exampleService; 29 | 30 | /** 31 | * 测试抛出运行时异常的处理. 32 | * 33 | * @return 直接返回,未处理 34 | */ 35 | @GetMapping("/test0") 36 | public UserInfoView test0() { 37 | exampleService.testUnCheckedException(); 38 | return UserInfoView.builder().id(0L).name("0000").build(); 39 | } 40 | 41 | /** 42 | * 测试抛出运行时异常的处理. 43 | * 44 | * @return 直接返回,未处理 45 | */ 46 | @GetMapping("/test1") 47 | public UserInfoView test1() throws Exception { 48 | exampleService.testCheckedException(); 49 | return UserInfoView.builder().id(0L).name("0000").build(); 50 | } 51 | 52 | @GetMapping("/customExceptionDetailMessage0") 53 | public void customExceptionDetailMessage0() { 54 | throw new ReplaceMsgException(); 55 | } 56 | 57 | @GetMapping("/customExceptionDetailMessage1") 58 | public void customExceptionDetailMessage1() { 59 | throw new ReplaceMsgException("我自己定义了异常信息"); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/GracefulResponseController.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefulresponse.GracefulResponse; 4 | import com.feiniaojin.gracefulresponse.GracefulResponseDataException; 5 | import com.feiniaojin.gracefuresponse.example.exceptions.ExceptionEnum; 6 | import io.swagger.v3.oas.annotations.tags.Tag; 7 | import org.springframework.util.Assert; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import java.util.Collections; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | @RestController 17 | @RequestMapping("/gr") 18 | @Tag(name = "GracefulResponse工具类演示接口", description = "演示GracefulResponse工具类的使用") 19 | public class GracefulResponseController { 20 | 21 | /** 22 | * 测试Controller中方法对参数进行校验的情形. 23 | * ... 24 | */ 25 | @GetMapping("/raiseException0") 26 | public void raiseException0() { 27 | GracefulResponse.raiseException("520", "测试手工异常0"); 28 | } 29 | 30 | /** 31 | * 测试Controller中方法对参数进行校验的情形. 32 | * ... 33 | */ 34 | @GetMapping("/raiseException1") 35 | public void raiseException1() { 36 | try { 37 | throw new Exception("发生异常啦"); 38 | } catch (Exception e) { 39 | GracefulResponse.raiseException("1314", "测试手工异常1", e); 40 | } 41 | } 42 | 43 | @GetMapping("/assert0") 44 | public void assert0(Integer id) { 45 | Assert.isTrue(id == 1, "id不等于1"); 46 | } 47 | 48 | @GetMapping("/assert1") 49 | public void assert1(Integer id) { 50 | GracefulResponse.wrapAssert(() -> Assert.isTrue(id == 1, "id不等于1")); 51 | } 52 | 53 | @GetMapping("/assert2") 54 | public void assert2(Integer id) { 55 | GracefulResponse.wrapAssert("1001", () -> Assert.isTrue(id == 1, "id不等于1")); 56 | Map data = new HashMap<>(); 57 | GracefulResponse.wrapAssert("1001", data, () -> Assert.isTrue(id == 1, "id不等于1")); 58 | } 59 | 60 | @GetMapping("/dataException0") 61 | public void dataException0() { 62 | GracefulResponse.raiseException(ExceptionEnum.CUSTOM_EXCEPTION, 63 | new GracefulResponseDataException(Collections.singletonMap("key", "value"))); 64 | } 65 | 66 | @GetMapping("/dataException") 67 | public void dataException() { 68 | throw new GracefulResponseDataException("测试dataException",Collections.singletonMap("key", "value")); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/config/ExampleConfig.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.config; 2 | 3 | import jakarta.validation.Validation; 4 | import jakarta.validation.Validator; 5 | import jakarta.validation.ValidatorFactory; 6 | import org.hibernate.validator.HibernateValidator; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.http.converter.HttpMessageConverter; 10 | import org.springframework.web.servlet.HandlerExceptionResolver; 11 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 12 | 13 | import java.util.List; 14 | 15 | /** 16 | * Config类. 17 | * 18 | * @author Yujie 19 | * @version 1.0 20 | * @mail qinyujie@gingo.cn 21 | * @date 23/1/2020 20:18:00 22 | */ 23 | @Configuration 24 | public class ExampleConfig implements WebMvcConfigurer { 25 | 26 | /** 27 | * 配置Validator的fail_fast. 28 | * 29 | * @return Validator 30 | */ 31 | @Bean 32 | public Validator validator() { 33 | ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class) 34 | .configure() 35 | .addProperty("hibernate.validator.fail_fast", "true") 36 | .buildValidatorFactory(); 37 | Validator validator = validatorFactory.getValidator(); 38 | return validator; 39 | } 40 | 41 | // @Override 42 | // public void configureMessageConverters(List> converters) { 43 | // FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); 44 | // //自定义配置... 45 | // FastJsonConfig config = new FastJsonConfig(); 46 | // config.setDateFormat("yyyy-MM-dd HH:mm:ss"); 47 | // config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean); 48 | // config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.PrettyFormat); 49 | // converter.setFastJsonConfig(config); 50 | // converter.setDefaultCharset(StandardCharsets.UTF_8); 51 | // converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); 52 | // converters.add(0, converter); 53 | // } 54 | 55 | 56 | @Override 57 | public void configureHandlerExceptionResolvers(List resolvers) { 58 | WebMvcConfigurer.super.configureHandlerExceptionResolvers(resolvers); 59 | } 60 | 61 | @Override 62 | public void configureMessageConverters(List> converters) { 63 | WebMvcConfigurer.super.configureMessageConverters(converters); 64 | } 65 | 66 | @Override 67 | public void extendMessageConverters(List> converters) { 68 | WebMvcConfigurer.super.extendMessageConverters(converters); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/ValidationController.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ValidationStatusCode; 4 | import com.feiniaojin.gracefuresponse.example.dto.*; 5 | import io.swagger.v3.oas.annotations.tags.Tag; 6 | import jakarta.validation.Valid; 7 | import jakarta.validation.constraints.NotNull; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.validation.annotation.Validated; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | @RestController 16 | @RequestMapping("/v") 17 | @Slf4j 18 | @Tag(name = "参数校验场景演示接口", description = "演示GracefulResponse对参数校验的支持") 19 | public class ValidationController { 20 | 21 | /** 22 | * http://localhost:9090/example/validateDto 23 | * 24 | * @param dto 25 | */ 26 | @PostMapping("/validateDto") 27 | // @ValidationStatusCode(code = "123") 28 | public void validateDto(@Validated UserInfoQuery dto) { 29 | log.info(dto.toString()); 30 | } 31 | 32 | /** 33 | * http://localhost:9090/example/validateDto 34 | * 35 | * @param dto 36 | */ 37 | @PostMapping("/validateDto1") 38 | @ValidationStatusCode(code = "123") 39 | public void validateDto1(@Validated UserInfoQuery dto) { 40 | log.info(dto.toString()); 41 | } 42 | 43 | /** 44 | * 测试Controller中方法对参数进行校验的情形. 45 | * http://localhost:9090/example/validateMethodParam 46 | * 47 | * @param userId 非空 48 | */ 49 | @PostMapping("/validateMethodParam") 50 | // @ValidationStatusCode(code = "1314") 51 | public void validateMethodParam(@NotNull(message = "userId不能为空") Long userId, 52 | @NotNull(message = "userName不能为空") Long userName) { 53 | log.info("" + userId); 54 | 55 | } 56 | 57 | /** 58 | * http://localhost:9090/example/validatePropertyList 59 | * 60 | * @param dto 61 | */ 62 | @PostMapping("/validatePropertyList") 63 | // @ValidationStatusCode(code = "523") 64 | public void validatePropertyList(@Valid @RequestBody PropertyListMethodDTO dto) { 65 | log.info(""); 66 | } 67 | 68 | /** 69 | * http://localhost:9090/example/validateMethodDto 70 | * 71 | * @param dto 72 | */ 73 | @PostMapping("/validateMethodDto") 74 | // @ValidationStatusCode(code = "523") 75 | public void validateMethodDto(@Validated @RequestBody MethodDTO dto) { 76 | log.info(""); 77 | } 78 | 79 | /** 80 | * http://localhost:9090/example/validate/propertyType 81 | * 82 | * @param command 83 | */ 84 | @PostMapping("/validate/propertyType") 85 | public void validatePropertyType(@RequestBody @Validated UserInfoCommand command) { 86 | log.info(""); 87 | } 88 | 89 | /** 90 | * @param classValidateCode 91 | */ 92 | @PostMapping("/classValidateCode") 93 | public void classValidateCode(@Validated @RequestBody ClassValidateCode classValidateCode) { 94 | 95 | } 96 | 97 | /** 98 | * http://localhost:9090/v/customValidation 99 | * 100 | * @param query 101 | */ 102 | @PostMapping("/customValidation") 103 | public void customValidation(@Validated CustomValidationUserQuery query) { 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/config/ApiDocsOperationCustomizer.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.config; 2 | 3 | import com.fasterxml.classmate.TypeResolver; 4 | import io.swagger.v3.oas.models.Operation; 5 | import io.swagger.v3.oas.models.media.*; 6 | import io.swagger.v3.oas.models.responses.ApiResponse; 7 | import io.swagger.v3.oas.models.responses.ApiResponses; 8 | import org.springdoc.core.customizers.OperationCustomizer; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.web.method.HandlerMethod; 12 | 13 | import java.util.Collections; 14 | import java.util.Map; 15 | import java.util.Objects; 16 | import java.util.Set; 17 | 18 | @Configuration 19 | public class ApiDocsOperationCustomizer implements OperationCustomizer { 20 | 21 | @Override 22 | public Operation customize(Operation operation, 23 | HandlerMethod handlerMethod) { 24 | 25 | ApiResponses responses = operation.getResponses(); 26 | Set> entrySet = responses.entrySet(); 27 | for (Map.Entry entry : entrySet) { 28 | if ("200".equals(entry.getKey())) { 29 | wrapSuccess(entry.getValue()); 30 | continue; 31 | } 32 | wrapError(entry.getValue()); 33 | } 34 | return operation; 35 | } 36 | 37 | private void wrapError(ApiResponse value) { 38 | final Content content = value.getContent(); 39 | if (Objects.isNull(content)) { 40 | return; 41 | } 42 | content.keySet().forEach(mediaTypeKey -> { 43 | final MediaType mediaType = content.get(mediaTypeKey); 44 | mediaType.schema(this.customizeSchemaError(mediaType.getSchema())); 45 | }); 46 | } 47 | 48 | private void wrapSuccess(ApiResponse value) { 49 | final Content content = value.getContent(); 50 | if (Objects.isNull(content)) { 51 | final Schema wrapperSchema = new Schema<>(); 52 | wrapperSchema.addProperty("code", new StringSchema()._default("200").description("错误码")); 53 | wrapperSchema.addProperty("msg", new StringSchema()._default("ok").description("提示信息")); 54 | wrapperSchema.addProperty("data", new MapSchema()._default(Collections.emptyMap()).description("响应数据体")); 55 | Content newContent = new Content(); 56 | MediaType mediaType = new MediaType(); 57 | mediaType.setSchema(wrapperSchema); 58 | newContent.put("*/*",mediaType); 59 | value.setContent(newContent); 60 | return; 61 | } 62 | content.keySet().forEach(mediaTypeKey -> { 63 | final MediaType mediaType = content.get(mediaTypeKey); 64 | mediaType.schema(this.customizeSchema(mediaType.getSchema())); 65 | }); 66 | } 67 | 68 | private Schema customizeSchema(final Schema objSchema) { 69 | final Schema wrapperSchema = new Schema<>(); 70 | wrapperSchema.addProperty("code", new StringSchema()._default("200").description("错误码")); 71 | wrapperSchema.addProperty("msg", new StringSchema()._default("ok").description("提示信息")); 72 | wrapperSchema.addProperty("data", objSchema); 73 | return wrapperSchema; 74 | } 75 | 76 | private Schema customizeSchemaError(final Schema objSchema) { 77 | final Schema wrapperSchema = new Schema<>(); 78 | wrapperSchema.addProperty("code", new StringSchema()._default("500").description("错误码")); 79 | wrapperSchema.addProperty("msg", new StringSchema()._default("error").description("提示信息")); 80 | return wrapperSchema; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.feiniaojin.ddd.ecosystem 8 | graceful-response-example 9 | 5.0.5-boot3 10 | 11 | 12 | UTF-8 13 | UTF-8 14 | UTF-8 15 | 16 | 17 | 18 | 19 | org.springframework.data 20 | spring-data-commons 21 | 22 | 23 | org.springdoc 24 | springdoc-openapi-starter-webmvc-api 25 | 2.6.0 26 | 27 | 28 | org.springdoc 29 | springdoc-openapi-starter-webmvc-ui 30 | 2.6.0 31 | 32 | 33 | com.github.xiaoymin 34 | knife4j-openapi3-jakarta-spring-boot-starter 35 | 4.4.0 36 | 37 | 38 | com.feiniaojin 39 | graceful-response 40 | 5.0.5-boot3 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter 45 | 3.4.1 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-web 50 | 3.4.1 51 | 52 | 53 | org.projectlombok 54 | lombok 55 | 1.18.24 56 | provided 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-logging 62 | 3.4.1 63 | 64 | 65 | slf4j-api 66 | org.slf4j 67 | 68 | 69 | 70 | 71 | com.alibaba.fastjson2 72 | fastjson2-extension-spring6 73 | 2.0.46 74 | 75 | 76 | 77 | 78 | 79 | 80 | org.springframework.boot 81 | spring-boot-dependencies 82 | 3.4.1 83 | pom 84 | import 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | org.springframework.boot 93 | spring-boot-maven-plugin 94 | 95 | 96 | org.apache.maven.plugins 97 | maven-compiler-plugin 98 | 3.11.0 99 | 100 | true 101 | 17 102 | 17 103 | 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /src/main/java/com/feiniaojin/gracefuresponse/example/controller/QuickStartController.java: -------------------------------------------------------------------------------- 1 | package com.feiniaojin.gracefuresponse.example.controller; 2 | 3 | import com.feiniaojin.gracefulresponse.api.ResponseFactory; 4 | import com.feiniaojin.gracefulresponse.data.Response; 5 | import com.feiniaojin.gracefuresponse.example.dto.PageBeanX; 6 | import com.feiniaojin.gracefuresponse.example.dto.UserInfoQuery; 7 | import com.feiniaojin.gracefuresponse.example.dto.UserInfoView; 8 | import io.swagger.v3.oas.annotations.Operation; 9 | import io.swagger.v3.oas.annotations.media.ArraySchema; 10 | import io.swagger.v3.oas.annotations.media.Content; 11 | import io.swagger.v3.oas.annotations.media.Schema; 12 | import io.swagger.v3.oas.annotations.responses.ApiResponse; 13 | import io.swagger.v3.oas.annotations.tags.Tag; 14 | import jakarta.annotation.Resource; 15 | import lombok.extern.slf4j.Slf4j; 16 | import org.springframework.data.domain.Page; 17 | import org.springframework.data.domain.PageImpl; 18 | import org.springframework.data.domain.Pageable; 19 | import org.springframework.validation.annotation.Validated; 20 | import org.springframework.web.bind.annotation.GetMapping; 21 | import org.springframework.web.bind.annotation.PostMapping; 22 | import org.springframework.web.bind.annotation.RequestMapping; 23 | import org.springframework.web.bind.annotation.RestController; 24 | 25 | import java.util.ArrayList; 26 | import java.util.Collections; 27 | import java.util.List; 28 | import java.util.Map; 29 | 30 | 31 | /** 32 | * class {@code ExampleController} 使用案例的Controller. 33 | * 34 | * @author qinyujie 35 | */ 36 | @RestController 37 | @RequestMapping("/qs") 38 | @Slf4j 39 | @Validated 40 | @Tag(name = "快速入门", description = "Graceful Response基本使用") 41 | public class QuickStartController { 42 | 43 | @Resource 44 | private ResponseFactory responseFactory; 45 | 46 | /** 47 | * 测试空返回值. 48 | * http://localhost:9090/qs/void 49 | */ 50 | @GetMapping("/void") 51 | public void testVoidResponse() { 52 | log.info("testVoidResponse"); 53 | } 54 | 55 | /** 56 | * 测试成功返回 57 | * http://localhost:9090/qs/get?id=1 58 | * 59 | * @param dto 入参 60 | * @return 61 | */ 62 | @GetMapping("/get") 63 | @ApiResponse(responseCode = "200", description = "查询成功", 64 | content = @Content(schema = @Schema(implementation = UserInfoView.class))) 65 | @Operation(summary = "查询用户信息", 66 | description = "根据ID查询用户信息") 67 | public UserInfoView get(UserInfoQuery dto) { 68 | return UserInfoView.builder().id(1L).name("name" + dto.getUserId()).build(); 69 | } 70 | 71 | /** 72 | * 测试成功返回 73 | * http://localhost:9090/qs/get?id=1 74 | * 75 | * @param dto 入参 76 | * @return 77 | */ 78 | @GetMapping("/list") 79 | @ApiResponse(responseCode = "200", description = "查询成功", 80 | content = @Content(array = @ArraySchema(schema = @Schema(implementation = UserInfoView.class)))) 81 | @Operation(summary = "查询用户信息列表", 82 | description = "查询用户信息列表") 83 | public List list(UserInfoQuery dto) { 84 | List list = new ArrayList<>(); 85 | for (long i = 1; i < 10L; i++) { 86 | list.add(UserInfoView.builder().id(i).name("name" + i).build()); 87 | } 88 | return list; 89 | } 90 | 91 | /** 92 | * 测试成功返回 93 | * http://localhost:9090/qs/pageList?id=1 94 | * 95 | * @return 96 | */ 97 | @GetMapping("/pageList") 98 | @ApiResponse(responseCode = "200", description = "查询成功") 99 | @Operation(summary = "分页查询用户信息列表", 100 | description = "分页查询用户信息列表") 101 | public Page pageList(Pageable pageable) { 102 | List list = new ArrayList<>(); 103 | for (long i = 0; i < 10L; i++) { 104 | list.add(UserInfoView.builder().id(i).name("name-" + i).build()); 105 | } 106 | return new PageImpl<>(list, pageable, 1000); 107 | } 108 | 109 | /** 110 | * 测试成功返回 111 | * http://localhost:9090/qs/pageList?id=1 112 | * 113 | * @return 114 | */ 115 | @GetMapping("/pageListGr") 116 | @ApiResponse(responseCode = "200", description = "查询成功") 117 | @Operation(summary = "分页查询用户信息列表", 118 | description = "分页查询用户信息列表") 119 | public PageBeanX pageListGr(Pageable pageable) { 120 | List list = new ArrayList<>(); 121 | for (long i = 0; i < 10L; i++) { 122 | list.add(UserInfoView.builder().id(i).name("name-" + i).build()); 123 | } 124 | PageBeanX pageBean = new PageBeanX<>(); 125 | pageBean.setPageSize(10); 126 | pageBean.setTotal(1000); 127 | pageBean.setPage(1); 128 | pageBean.setList(list); 129 | return pageBean; 130 | } 131 | 132 | /** 133 | * 测试抛出运行时异常的处理. 134 | * http://localhost:9090/qs/runtime 135 | * 136 | * @return 直接返回,未处理 137 | */ 138 | @GetMapping("/runtime") 139 | public UserInfoView testRuntimeException() { 140 | throw new RuntimeException(); 141 | } 142 | 143 | /** 144 | * 测试受检异常的情形. 145 | * http://localhost:9090/qs/checked 146 | * 147 | * @param dto 入参 148 | * @return 未处理,直接将入参返回 149 | * @throws Exception 受检异常 150 | */ 151 | @GetMapping("/checked") 152 | public UserInfoView testCheckedException(UserInfoQuery dto) throws Exception { 153 | throw new Exception(); 154 | } 155 | 156 | /** 157 | * 测试抛出{@code Throwable} 的情形. 158 | * http://localhost:9090/qs/throwable 159 | * 160 | * @param dto 入参 161 | * @return 未处理,直接返回 162 | * @throws Throwable 抛出Throwable异常 163 | */ 164 | @GetMapping("/throwable") 165 | public UserInfoView testThrowable(UserInfoQuery dto) throws Throwable { 166 | log.info(dto.toString()); 167 | throw new Throwable(); 168 | } 169 | 170 | /** 171 | * http://localhost:9090/qs/jsonStr 172 | *

173 | * {"key":"value"} 174 | * 测试Controller中方法对参数进行校验的情形. 175 | */ 176 | @GetMapping("/jsonStr") 177 | public Response jsonStr() { 178 | return responseFactory.newSuccessInstance("abc"); 179 | } 180 | 181 | /** 182 | * http://localhost:9090/qs/str 183 | * 直接返回String,将会匹配模版页面. 184 | */ 185 | @GetMapping("/str") 186 | public String str() { 187 | log.info(""); 188 | return "view"; 189 | } 190 | 191 | /** 192 | * http://localhost:9090/example/return/str 193 | * 直接返回String 194 | */ 195 | @GetMapping("/return/str") 196 | public String returnStr() { 197 | return "测试成功"; 198 | } 199 | 200 | @GetMapping("/kv") 201 | public Map kv() { 202 | return Collections.singletonMap("key", "token"); 203 | } 204 | 205 | /** 206 | * 不支持的http方法调用. 207 | * POST接口,使用GET进行请求 208 | * http://localhost:9090/example/methodPost 209 | * 210 | * @param userId 非空 211 | */ 212 | @PostMapping(value = "/methodPost") 213 | public void testMethodNotSupport(Long userId) { 214 | log.info("收到入参userId={}", userId); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------