Spring Cloud Spring Boot mybatis分布式微服务云架构(十二)返回JSON格式
2018-03-01 09:02
831 查看
在上述例子中,通过
本质上,只需在
下面以一个具体示例来实现返回JSON格式的异常处理。
创建统一的JSON返回对象,code:消息类型,message:消息内容,url:请求的url,data:请求返回的数据
创建一个自定义异常,用来实验捕获该异常,并返回json
为
启动应用,访问:http://localhost:8080/json,可以得到如下返回内容:
源码来源
@ControllerAdvice统一定义不同Exception映射到不同错误处理页面。而当我们要实现RESTful API时,返回的错误是JSON格式的数据,而不是HTML页面,这时候我们也能轻松支持。
本质上,只需在
@ExceptionHandler之后加入
@ResponseBody,就能让处理函数return的内容转换为JSON格式。
下面以一个具体示例来实现返回JSON格式的异常处理。
创建统一的JSON返回对象,code:消息类型,message:消息内容,url:请求的url,data:请求返回的数据
public class ErrorInfo<T> { public static final Integer OK = 0; public static final Integer ERROR = 100; private Integer code; private String message; private String url; private T data; // 省略getter和setter }
创建一个自定义异常,用来实验捕获该异常,并返回json
public class MyException extends Exception { public MyException(String message) { super(message); } }
Controller中增加json映射,抛出
MyException异常
@Controller public class HelloController { @RequestMapping("/json") public String json() throws MyException { throw new MyException("发生错误2"); } }
为
MyException异常创建对应的处理
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = MyException.class) @ResponseBody public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception { ErrorInfo<String> r = new ErrorInfo<>(); r.setMessage(e.getMessage()); r.setCode(ErrorInfo.ERROR); r.setData("Some Data"); r.setUrl(req.getRequestURL().toString()); return r; } }
启动应用,访问:http://localhost:8080/json,可以得到如下返回内容:
{ code: 100, data: "Some Data", message: "发生错误2", url: "http://localhost:8080/json" }至此,已完成在Spring Boot中创建统一的异常处理,实际实现还是依靠Spring MVC的注解,更多更深入的使用可参考Spring MVC的文档。
源码来源
相关文章推荐
- Spring Cloud Spring Boot mybatis分布式微服务云架构(十二)返回JSON格式
- Spring Cloud Spring Boot mybatis分布式微服务云架构(十二)返回JSON格式
- Spring Cloud Spring Boot mybatis分布式微服务云架构(十二)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(十八)使用Spring-data-jpa(2)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(九)使用Swagger2构建强大的RESTful API文档(1)
- spring cloud + spring boot + springmvc+mybatis分布式微服务云架构
- Spring Cloud Spring Boot mybatis分布式微服务云架构(七)开发Web应用(1)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(四十一)实现Web层的日志切面
- Spring Cloud Spring Boot mybatis分布式微服务云架构(十三)使用Spring Security安全控制
- Spring Cloud Spring Boot mybatis分布式微服务云架构(五)构建RESTful API
- Spring Cloud Spring Boot mybatis分布式微服务云架构(三)属性配置文件详解(1)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(二)使用Intellij中的Spring Initializr来快速构建Spring Boot/Cloud工程
- Spring Cloud Spring Boot mybatis分布式微服务云架构(八)开发Web应用(2)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(十)使用Swagger2构建强大的RESTful API文档(2)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(十一)Web应用的统一异常处理
- SpringCloud SpringBoot mybatis 分布式微服务(十二)Spring Boot中使用Redis数据库
- Spring Cloud Spring Boot mybatis分布式微服务云架构(三十七)日志管理
- Spring Cloud Spring Boot mybatis分布式微服务云架构(二十五)整合MyBatis
- Spring Cloud Spring Boot mybatis分布式微服务云架构(四)属性配置文件详解(2)
- Spring Cloud Spring Boot mybatis分布式微服务云架构(四)属性配置文件详解(2)