t org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping
public class NoResultWarpperController {
@PostMapping("hello")
public HelloDto hello(@RequestBody HelloCmd name){
HelloDto result = new HelloDto();
result.setResult("hello,"+name);
return result;
}
@Data
public class HelloCmd{
private String name;
}
@Data
public class HelloDto{
private String result;
}
}
测试代码如下
@SpringBootTest
@AutoConfigureMockMvc
public class NoResultWarpperControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHello() throws Exception{
ObjectMapper map = new ObjectMapper();
NoResultWarpperController.HelloCmd cmd = new NoResultWarpperController.HelloCmd();
cmd.setName("zhangsan");
String body = map.writeValueAsString(cmd);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/hello")
.contentType(MediaType.APPLICATION_JSON)
.content(body)
).andReturn();
assertThat(mvcResult.getResponse().getStatus()).isEqualTo(200);
NoResultWarpperController.HelloDto dto = map.readValue(mvcResult.getResponse().getContentAsString(), NoResultWarpperController.HelloDto.class);
assertThat(dto).isNotNull();
assertThat(dto.getResult()).isEqualTo("hello,zhangsan");
}
}
方式一,Controller方法统一返回类型ApiResult
新建统一返回类
@Data
public class ApiResult {
private T result;
private boolean success;
private String errorCode;
private String errorMessage;
private String errorDetail;
}
修改上面例子的Controller, 方法返回ApiResult
@RestController()
@RequestMapping
public class NoResultWarpperController {
@PostMapping("hello")
public ApiResult hello(@RequestBody HelloCmd cmd){
HelloDto result = new HelloDto();
result.setResult("hello,"+ cmd.getName());
return new ApiResult<>(result);
}
}
测试代码
@Test
public void testHello() throws Exception{
ObjectMapper map = new ObjectMapper();
NoResultWarpperController.HelloCmd cmd = new NoResultWarpperController.HelloCmd();
cmd.setName("zhangsan");
String body = map.writeValueAsString(cmd);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/hello")
.contentType(MediaType.APPLICATION_JSON)
.content(body)
).andReturn();
assertThat(mvcResult.getResponse().getStatus()).isEqualTo(200);
ApiResult dto = map.readValue(mvcResult.getResponse().getContentAsString(),
new TypeReference>(){});
assertThat(dto).isNotNull();
assertThat(dto.isSuccess()).isTrue();
assertThat(dto.getResult().getResult()).isEqualTo("hello,zhangsan");
}
@RestController()
@RequestMapping
public class NoResultWarpperController {
@PostMapping("hello")
public HelloDto hello(@RequestBody HelloCmd cmd){
HelloDto result = new HelloDto();
result.setResult("hello,"+ cmd.getName());
return result;
}
}
@PostMapping("helloNoWrap")
@DontWrapResult
public HelloDto helloNoWrap(@RequestBody HelloCmd cmd){
HelloDto result = new HelloDto();
result.setResult("hello,"+ cmd.getName());
return result;
}
修改拦截器,是的@DontWrapResult 注解的方法或类直接返回结果
@SneakyThrows
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class extends HttpMessageConverter>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (methodParameter.hasMethodAnnotation(DontWrapResult.class)){
return body;
}
if (AnnotationUtils.findAnnotation(methodParameter.getDeclaringClass(),DontWrapResult.class)!=null){
return body;
}
ObjectMapper mapper = new ObjectMapper();
if (body instanceof ApiResult){
return body;
}
// 包装 string 类型
if(body instanceof String){
return mapper.writeValueAsString(new ApiResult<>(body));
}
return new ApiResult<>(body);
}
添加测试代码
@Test
public void testHelloNoWrap() throws Exception{
ObjectMapper map = new ObjectMapper();
NoResultWarpperController.HelloCmd cmd = new NoResultWarpperController.HelloCmd();
cmd.setName("liubei");
String body = map.writeValueAsString(cmd);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/helloNoWrap")
.contentType(MediaType.APPLICATION_JSON)
.content(body)
).andReturn();
assertThat(mvcResult.getResponse().getStatus()).isEqualTo(200);
NoResultWarpperController.HelloDto dto = map.readValue(mvcResult.getResponse().getContentAsString(),
NoResultWarpperController.HelloDto.class);
assertThat(dto).isNotNull();
assertThat(dto.getResult()).isEqualTo("hello,liubei");
}
异常
统一返回类型后,全局异常也要包装到类型ApiResult
定义友好的业务异常类UserFriendlyException
public class UserFriendlyException extends Exception{
private int code;
public int errorCode(){
return code;
}
public UserFriendlyException(){}
public UserFriendlyException(String msg){
super(msg);
}
public UserFriendlyException(int code, String msg){
this(msg);
this.code= code;
}
}
修改拦截器,进行异常拦截
@ExceptionHandler(Exception.class)
@ResponseBody
public ApiResult
普通异常测试
Controller 添加 除法运算
@GetMapping("div")
public Double div(){
throw new RuntimeException("b is zero");
}
测试
@Test
public void testDiv() throws Exception {
ObjectMapper map = new ObjectMapper();
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/div")
).andReturn();
assertThat(mvcResult.getResponse().getStatus()).isEqualTo(500);
assertThat(mvcResult.getResponse().getContentAsString()).isNotNull();
ApiResult errorInfo = map.readValue(mvcResult.getResponse().getContentAsString(), new TypeReference>(){});
assertThat(errorInfo).isNotNull();
assertThat(errorInfo.getErrorCode()).isEqualTo(500);
assertThat(errorInfo.getErrorMessage()).isEqualTo("b is zero");
}
友好异常
Controller 添加 加法运算
@GetMapping("add")
public void add() throws UserFriendlyException {
throw new UserFriendlyException(10000, "no method");
}
Edo Interactive在几年前遇到一个大问题:公司使用交易数据来帮助零售商和餐馆进行个性化促销,但其数据仓库没有足够时间去处理所有的信用卡和借记卡交易数据
“我们要花费27小时来处理每日的数据量,”Edo主管基础设施和信息系统的高级副总裁Tim Garnto说道:“所以在2013年,我们放弃了现有的基于PostgreSQL的关系型数据库系统,使用了Hadoop集群作为公司的数
例如我们把scott.dept表生成文本文件的语句写成dept.sql,内容如下:
set pages 50000;
set lines 200;
set trims on;
set heading off;
spool /oracle_backup/log/test/dept.lst;
select deptno||','||dname||','||loc
1. Download and unzip the SonarQube distribution
2. Starting the Web Server
The default port is "9000" and the context path is "/". These values can be changed in &l
昨天在为了把laravel升级到最新的版本,突然之间就出现了如下错误:
ErrorException thrown with message "Declaration of Illuminate\View\Engines\CompilerEngine::handleViewException() should be compatible with Illuminate\View\Eng
import java.util.Arrays;
import java.util.Random;
public class Nim {
/**编程之美 NIM游戏分析
问题:
有N块石头和两个玩家A和B,玩家A先将石头随机分成若干堆,然后按照BABA...的顺序不断轮流取石头,
能将剩下的石头一次取光的玩家获胜,每次取石头时,每个玩家只能从若干堆石头中任选一堆,
今天在测试环境使用yum安装,遇到一个问题:
Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again
处理很简单,修改文件“/etc/yum.repos.d/epel.repo”, 将baseurl的注释取消, mirrorlist注释掉。即可。
&n
今天在linux下做hbase集群的时候,发现hmaster启动成功了,但是用hbase命令进入shell的时候报了一个错误 PleaseHoldException: Master is initializing,查看了日志,大致意思是说master和slave时间不同步,没办法,只好找一种手动同步一下,后来发现一共部署了10来台机器,手动同步偏差又比较大,所以还是从网上找现成的解决方