本文章僅供小編學習使用,如有侵犯他人版權,請聯(lián)系小編撤回或刪除
GIt地址:https://github.com/mysupermans/CustomException-Rest.git
先看下目錄結構
一、統(tǒng)一返回類型結構
為什么要統(tǒng)一格式开泽?
我們使用SpringBoot編寫接口的時候,最好是返回一個統(tǒng)一格式的JSON,該格式包含錯誤碼羊异,附帶信息,以及攜帶的數(shù)據(jù)彤断。這樣前端在解析的時候就能統(tǒng)一解析野舶,同時攜帶錯誤碼可以更加容易的排查錯誤。
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 定義統(tǒng)一的系統(tǒng)基本返回類型
/**
* @program: workspace
* @description: 系統(tǒng)基本返回類型
* @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體進行統(tǒng)一返回
/**
* @program: workspace
* @description: 對restcontroller的body體進行統(tǒng)一返回
* @author: 劉宗強
* @create: 2019-08-27 16:59
**/
@ControllerAdvice
public class BaseResponseBodyAdvice implements ResponseBodyAdvice<Object> {
/**
* 這個方法表示對于哪些請求要執(zhí)行beforeBodyWrite一屋,返回true執(zhí)行,返回false不執(zhí)行
*/
@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));
}
//如果已經(jīng)被異常捕獲,返回的就是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 后端參數(shù)校驗
*/
@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
解決方案:http://www.reibang.com/p/aacf72d6bf6f
配置一個消息轉(zhuǎn)換器就可以了
二轧苫、統(tǒng)一異常處理
1、新建一個ErrorType 枚舉類,用于定義系統(tǒng)錯誤類型
/**
* @program: workspace
* @description: 系統(tǒng)錯誤類型
* @author: 劉宗強
* @create: 2019-08-27 10:04
**/
public enum ErrorType {
//資源參數(shù)問題
PARAM_INVALID(-1, "參數(shù)不合法"),
NOT_FOUND(2, "不存在此資源"),
ALREADY_EXISTS(3, "資源已經(jīng)存在,不能重復"),
PARAMS_NULL(3, "參數(shù)不能為空"),
//身份方面問題
REQUEST_OUT_OF_TIME(4, "請求過期"),
AUTHENTICATION_FAILED(100, "身份認證失敗"),
REQUEST_METHOD_ERROR(101, "請求類型不支持"),
OPERATION_SCOPE_FAILED(102, "不支持此操作"),
//系統(tǒng)基本碼
ERROR(0, "系統(tǒng)異常"),
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);
}
}
結果: