package demo.utils;
import com.alibaba.fastjson.JSON;
import demo.controller.ProductController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Controller全局错误捕获类
*/
@RestControllerAdvice //拦截异常并统一处理
public class ExceptionIntercept {
public static final String PLAT_ERROR = "PLAT_ERROR";
// Logger和LogManager导入的是org.apache.logging包
private static final Logger logger = LogManager.getLogger(ProductController.class);
@ExceptionHandler(Exception.class)
public MessagePack handler(Exception ex) {
//返回错误数据包
MessagePack pack = new MessagePack();
pack.setCode(MessagePack.ERROR);
pack.setMessage(ex.getMessage());
pack.setStatus(PLAT_ERROR);
//同时记录错误日志
logger.error("Controller全局错误捕获类==>" + JSON.toJSONString(pack));
return pack;
}
}
package demo.utils;
import com.alibaba.fa