sharp-common
集成Spring Web主要体现在以下3个方面
- 通过注解
@RestControllerAdvice
封装异常异常ApiExceptionHandler
- 注入国际化的工具类
MessageUtils
- 封装
Result
返回对象
集成
- 添加包扫描,将
ApiExceptionHandler
和MessageUtils
纳入Spring上下文,@EnableResultWrapped
自动包裹Result
对象。
@Configuration
@Import({ApiExceptionHandler.class, MessageUtils.class})
@EnableResultWrapped
public class MvcConfig implements WebMvcConfigurer {}
- 国际化文件
# messages_en_US.properties
BEAN_VALIDATE_ERROR=Params validate error:{0}
MAX_TRY_LOGIN_ERROR=The account failed to log in {0} times, please wait {1} minutes and try again
# messages_zh_CN.properties
BEAN_VALIDATE_ERROR=参数验证错误:{0}
MAX_TRY_LOGIN_ERROR=该账号{0}次登录失败后,被锁定{1}分钟
- 添加业务异常枚举
@Getter
@ToString
public enum ExceptionCode {
BEAN_VALIDATE_ERROR(30002, "BEAN_VALIDATE_ERROR"),
PRICE_CRAWLER_ERROR(40004, "网站价格获取失败");
private int code;
private String msg;
ExceptionCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
public ExceptionResult<String> result() {
return new ExceptionResult<>(getCode(), getMsg());
}
}
BEAN_VALIDATE_ERROR
在国际化文件中进行了语言维护。
测试
@RestController
@RequestMapping("test")
public class TestController {
@GetMapping("1")
public Result test1() {
return ResultUtils.success(MessageUtils.getMessage("MAX_TRY_LOGIN_ERROR", new Object[] {5, 20}));
}
@GetMapping("2")
public Result test2() {
int a = 1 / 0;
return ResultUtils.success();
}
@GetMapping("3")
public Result test3() {
return ResultUtils.fail();
}
@GetMapping("4")
public Result test4() {
throw new BizException(ExceptionCode.FORMULA_ERROR.result());
}
@GetMapping("5")
public Result test5() {
throw new BizException(ExceptionCode.BEAN_VALIDATE_ERROR.result(), new Object[] {"姓名不能为空"});
}
@GetMapping("6")
public int test5() {
return 1;
}
@GetMapping("7")
@UnWrapped
public int test7() {
return 7;
}
}
注解 @UnWrapped
表示不需要被 Result
对象包裹。