本文章仅供小编学习使用,如有侵犯他人版权,请联系小编撤回或删除
GIt地址:https://github.com/mysupermans/CustomException-Rest.git
先看下目录结构
一、统一返回类型结构
为什么要统一格式?
我们使用SpringBoot编写接口的时候,最好是返回一个统一格式的JSON,该格式包含错误码,附带信息,以及携带的数据。这样前端在解析的时候就能统一解析,同时携带错误码可以更加容易的排查错误。
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>log-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>log-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!-- 自动重启 -->
<configuration>
<fork>true</fork>
<!-- 如果没有该项配置,肯呢个devtools不会起作用,即应用不会restart -->
</configuration>
</plugin>
</plugins>
</build>
</project>
1、新建 BaseResponse 定义统一的系统基本返回类型
/**
* @program: workspace
* @description: 系统基本返回类型
* @author: 刘宗强
* @create: 2019-08-27 10:34
**/
public class BaseResponse<T> {
private int code;
private String message;
private T data;
public BaseResponse(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public BaseResponse(T data, ErrorType errorType){
this.code=errorType.getCode();
this.message=errorType.getMessage();
this.data=data;
}
public BaseResponse(ErrorType errorType){
this.code=errorType.getCode();
this.message=errorType.getMessage();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
2、新建 BaseResponseBodyAdvice类 对restcontroller的body体进行统一返回
/**
* @program: workspace
* @description: 对restcontroller的body体进行统一返回
* @author: 刘宗强
* @create: 2019-08-27 16:59
**/
@ControllerAdvice
public class BaseResponseBodyAdvice implements ResponseBodyAdvice<Object> {
/**
* 这个方法表示对于哪些请求要执行beforeBodyWrite,返回true执行,返回false不执行
*/
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
/**
* 对于返回的对象如果不是最终对象ResponseResult,则选包装一下
*/
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
/**
* 验证方面的特殊处理
*/
HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
if(httpServletRequest.getAttribute(ErrorType.class.getSimpleName()) != null){
System.out.println(ErrorType.class.getSimpleName());
ErrorType errorType = (ErrorType)httpServletRequest.getAttribute(ErrorType.class.getSimpleName());
return JSONObject.toJSON(new BaseResponse<>(errorType));
}
//如果是字符类型,输出json字符串
if(mediaType.includes(MediaType.TEXT_HTML)||mediaType.includes(MediaType.TEXT_PLAIN)){
return JSONObject.toJSON(new BaseResponse<>(body, ErrorType.SUCCESS));
}
//如果已经被异常捕获,返回的就是BaseResponse对象,不用再次封装了
if (body instanceof BaseResponse<?>) {
return body;
}
return new BaseResponse<>(body, ErrorType.SUCCESS);
}
}
3、新建 User 模型类 待会做测试用
/**
* @program: workspace
* @description:
* @author: 刘宗强
* @create: 2019-08-26 16:02
**/
@Data
@AllArgsConstructor
public class User {
private String userName;
@NotNull(message = "年龄不能为空!")
private Integer Age;
}
4、测试
/**
* @program: log-demo
* @description:
* @author: 刘宗强
* @create: 2019-08-26 12:02
**/
@RestController
@RequestMapping("test")
@Slf4j
public class TestController {
/**
* 测试Validated 后端参数校验
*/
@PostMapping("/addUser")
public User testPost(@RequestBody @Validated User user){
return user;
}
/**
* 返回对象信息
*/
@GetMapping("/getUser")
public User getUser(){
User user=new User("liuzongqiang",22);
return user;
}
/**
* 返回字符串
*/
@GetMapping("/getStr")
public String getStr(){
return "hello";
}
}
结果:
在返回string类型时报:
com.alibaba.fastjson.JSONObject cannot be cast to java.lang.String
解决方案:https://www.jianshu.com/p/aacf72d6bf6f
配置一个消息转换器就可以了
二、统一异常处理
1、新建一个ErrorType 枚举类,用于定义系统错误类型
/**
* @program: workspace
* @description: 系统错误类型
* @author: 刘宗强
* @create: 2019-08-27 10:04
**/
public enum ErrorType {
//资源参数问题
PARAM_INVALID(-1, "参数不合法"),
NOT_FOUND(2, "不存在此资源"),
ALREADY_EXISTS(3, "资源已经存在,不能重复"),
PARAMS_NULL(3, "参数不能为空"),
//身份方面问题
REQUEST_OUT_OF_TIME(4, "请求过期"),
AUTHENTICATION_FAILED(100, "身份认证失败"),
REQUEST_METHOD_ERROR(101, "请求类型不支持"),
OPERATION_SCOPE_FAILED(102, "不支持此操作"),
//系统基本码
ERROR(0, "系统异常"),
SUCCESS(1, "成功");
private int code;
private String message;
ErrorType(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2、新建 CustomException 自定义异常类
/**
* @program: workspace
* @description: 用户自定义异常
* @author: 刘宗强
* @create: 2019-08-27 11:56
**/
public class CustomException {
@Data
@Accessors(chain = true)
@AllArgsConstructor
public static class ParamInvalidException extends RuntimeException{
private Map<String,Object> params;
}
@Data
@Accessors(chain = true)
@AllArgsConstructor
public static class NotFoundException extends RuntimeException{
private Map<String,Object> params;
}
@Data
@Accessors(chain = true)
@AllArgsConstructor
public static class AlreadyExistsException extends RuntimeException{
private Map<String,Object> params;
}
@Data
@Accessors(chain = true)
@AllArgsConstructor
public static class ParamNullException extends RuntimeException{
private Map<String,Object> params;
}
}
3、新建 BaseControllerAdvice 全局异常处理控制器
/**
* controller异常拦截,关键应用可从异常中获取有用信息并做日志记录
*/
@ControllerAdvice
public class BaseControllerAdvice {
@ResponseBody
@ExceptionHandler(Exception.class)
public BaseResponse<String> sysError(Exception e){
return new BaseResponse<>(null,ErrorType.ERROR.getCode(),e.getMessage()==null?String.valueOf(e):ErrorType.ERROR.getMessage());
}
@ResponseBody
@ExceptionHandler(IllegalArgumentException.class)
public BaseResponse<String> argumentError(IllegalArgumentException e){
return new BaseResponse<>(null,ErrorType.PARAM_INVALID.getCode(),e.getLocalizedMessage()==null?String.valueOf(e):e.getLocalizedMessage());
}
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public BaseResponse<String> validateException(MethodArgumentNotValidException e){
final List<String> errList = new ArrayList<>();
e.getBindingResult().getAllErrors().stream().forEach(x-> {
errList.add(x.getDefaultMessage());
});
return new BaseResponse<>("",ErrorType.PARAM_INVALID.getCode(),errList.toString());
}
@ResponseBody
@ExceptionHandler(ParamInvalidException.class)
public BaseResponse<?> paramInvalidException(ParamInvalidException e){
return new BaseResponse<>(e.getParams(),ErrorType.PARAM_INVALID);
}
@ResponseBody
@ExceptionHandler(NotFoundException.class)
public BaseResponse<?> notFoundException(NotFoundException e){
return new BaseResponse<>(e.getParams(),ErrorType.NOT_FOUND);
}
@ResponseBody
@ExceptionHandler(AlreadyExistsException.class)
public BaseResponse<?> alreadyExistsException(AlreadyExistsException e){
return new BaseResponse<>(e.getParams(),ErrorType.ALREADY_EXISTS);
}
@ResponseBody
@ExceptionHandler(ParamNullException.class)
public BaseResponse<?> paramNullException(ParamNullException e){
return new BaseResponse<>(e.getParams(),ErrorType.PARAMS_NULL);
}
@ResponseBody
@ExceptionHandler(ImageUploadException.class)
public BaseResponse<?> imageUploadException(ImageUploadException e){
return new BaseResponse<>(e.getOriginFileUrl(),ErrorType.IMG_UPLOAD_ERR);
}
@ResponseBody
@ExceptionHandler(ImageNullException.class)
public BaseResponse<?> imageNullException(ImageNullException e){
return new BaseResponse<>(e.getParams(),ErrorType.IMG_NOT_NULL);
}
@ResponseBody
@ExceptionHandler(OssImageFailDelException.class)
public BaseResponse<?> ossImageFailDelException(OssImageFailDelException e){
return new BaseResponse<>(e.getParams(),ErrorType.OSS_FAIL_DEL);
}
@ResponseBody
@ExceptionHandler(InventoryUnEnoughException.class)
public BaseResponse<?> inventoryUnEnough(InventoryUnEnoughException e){
return new BaseResponse<>(e.getParams(),ErrorType.PRODUCT_INVENTORY_UNENOUGH);
}
}
4、测试
/**
* @program: log-demo
* @description:
* @author: 刘宗强
* @create: 2019-08-26 12:02
**/
@RestController
@RequestMapping("test")
@Slf4j
public class TestController {
@GetMapping("")
public String test(){
Map<String,Object> map=new HashMap<>();
map.put("id","12");
throw new CustomException.NotFoundException(map);
}
}
结果: