import com.sun.java.browser.plugin2.liveconnect.v1.Result;
import com.techno.util.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 捕获异常的类,返回信息给浏览器,可以自定义返回的code,msg等信息
*/
@ControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseData handle(Exception e) {
ResponseData res = ResponseData.serverInternalError();
if (e instanceof OwnException) { //判断异常是否是我们定义的异常
OwnException ownException = (OwnException) e;
return res.putDataValue(ownException.getCode()+"", ownException.getMessage());
}else {
logger.error("【系统异常】{}", e);
return res.putDataValue("-1", "系统异常");
}
}
}
class OwnException extends RuntimeException{ //注意:spring中,只有RuntimeException才会进行事务回滚,Exception不会进行事务回滚
private Integer code;
public OwnException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
enum ResultEnum {
UNKONW_ERROR(-1, "未知错误"),
SERVER_ERROR(500,"系统异常"),
SUCCESS(0, "成功"),
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
@ControllerAdvice会拦截系统controller或service抛出的异常