该类不需要controller继承!!!
package com.smallk.controller.base;
import com.smallk.common.Const;
import com.smallk.utils.BusinessException;
import com.smallk.utils.HttpUtil;
import com.smallk.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 异常处理
*
* @author smallk
* @date 2018/10/28 23:04
*/
@Slf4j
@ControllerAdvice
public class ExceptionHandlerController {
private static final String XHR = "XMLHttpRequest";
/**
* Global exception handling
*/
@ExceptionHandler
public String errorSkip(HttpServletRequest request, HttpServletResponse response, Exception e) {
String xmlHttpRequest = request.getHeader("X-Requested-With");
if (XHR.equals(xmlHttpRequest)) {
JsonResult res = new JsonResult();
if (e instanceof BusinessException) {
res.setMsg(e.getMessage());
res.setStatus(Const.BUSINESS_EXCEPTION);
HttpUtil.toJson(res, response);
} else {
log.error("", e);
e.printStackTrace();
res.setMsg("Request error");
res.setStatus(Const.AJAX_ERROR);
response.setHeader("AJAX_ERROR", Const.AJAX_ERROR);
HttpUtil.toJson(res, response);
}
return null;
}
log.error("", e);
e.printStackTrace();
return "error/error";
}
}
网友评论