1.定義返回類
package com.eternalray.common;
import lombok.Data;
/**
* @Author: Eternalray
* 返回結果集公用方法
*/
@Data
public class Result<T> {
/**
* success 是否成功返回結果 成功true 失敗false
*/
private boolean success;
/**
* data 返回的結果數據
*/
private T data;
public static <T> Result<T> set(boolean success,T data){
Result<T> result=new Result<>();
result.setSuccess(success);
result.setData(data);
return result;
}
}
2.定義異常類
package com.eternalray.conf;
import com.eternalray.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.lang.reflect.UndeclaredThrowableException;
/**
* 全局異常處理配置
* @author EternalRay
*/
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandleConf {
/**
* 頂級異常處理
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public Object handlerException(Exception e){
//annotation拋出的異常
if(e instanceof UndeclaredThrowableException) {
e = (Exception) ((UndeclaredThrowableException)e).getUndeclaredThrowable();
}
log.error("[handleException]: ",e);
return Result.set(false,e.getMessage());
}
}