Files
SOP/doc/docs/files/10040_错误处理.md
2019-03-25 11:49:16 +08:00

91 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 错误处理
SOP对错误处理已经封装好了简单做法是`throw ServiceException`在最顶层的Controller会做统一处理。例如
```java
if(StringUtils.isEmpty(param.getGoods_name())) {
throw new ServiceException("goods_name不能为null");
}
```
为了保证编码风格的一致性推荐统一使用ServiceException
## i18n国际化
SOP支持国际化消息。通过Request对象中的getLocale()来决定具体返回那种语言客户端通过设置Accept-Language头部来决定返回哪种语言中文是zh英文是en。
SOP通过模块化来管理国际化消息这样做的好处结构清晰维护方便。下面就来讲解如何设置国际化消息。
以story服务为例假设我们要对商品模块进行设置步骤如下
-`resource/i18n/isp`目录下新建goods_error_zh_CN.properties属性文件
属性文件的文件名有规律, **i18n/isp/goods_error** 表示模块路径, **_zh_CN.properties** 表示中文错误消息。如果要使用英文错误,则新建一个`goods_error_en.properties`即可。
- 在goods_error_zh_CN.properties中配置错误信息
```
# 商品名字不能为空
isp.goods_error_100=\u5546\u54C1\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
```
isp.goods_error_为固定前缀100为错误码这两个值后续会用到。
接下来是把属性文件加载到国际化容器当中。
- 添加国际化配置在OpenServiceConfig中的static块中添加代码如下
```java
@Configuration
public class OpenServiceConfig extends AlipayServiceConfiguration {
static {
ServiceConfig.getInstance().getI18nModules().add("i18n/isp/goods_error");
}
}
```
- 新建一个枚举用来定义错误
```java
// 按模块来定义异常消息,团队开发可以分开进行
public enum GoodsErrorEnum {
/** 参数错误 */
NO_GOODS_NAME("100"),
;
private ServiceErrorMeta errorMeta;
StoryErrorEnum(String subCode) {
this.errorMeta = new ServiceErrorMeta("isp.goods_error_", subCode);
}
public ServiceErrorMeta getErrorMeta() {
return errorMeta;
}
}
```
接下来就可以使用了
```java
if (StringUtils.isEmpty(param.getGoods_name())) {
throw GoodsErrorEnum.NO_GOODS_NAME.getErrorMeta().getException();
}
```
### 国际化消息传参
即代码中变量传入到properties文件中去做法是采用{0},{1}占位符。0代表第一个参数1表示第二个参数。
```
# 商品名称太短,不能小于{0}个字
isp.goods_error_101=\u5546\u54C1\u540D\u79F0\u592A\u77ED\uFF0C\u4E0D\u80FD\u5C0F\u4E8E{0}\u4E2A\u5B57
```
```java
if (param.getGoods_name().length() <= 3) {
throw GoodsErrorEnum.LESS_GOODS_NAME_LEN.getErrorMeta().getException(3);
}
```
直接放进getException(Object... params)方法参数中,因为是可变参数,可随意放。