自动化立体仓库 - WMS系统
skyouc
昨天 e26b2f48c63d8b6a7757e1e8c4f04e006ccfbfe9
src/main/java/com/zy/common/config/CoolExceptionHandler.java
@@ -6,6 +6,9 @@
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by vincent on 2019-06-09
@@ -14,19 +17,67 @@
public class CoolExceptionHandler {
    @ExceptionHandler(Exception.class)
    public R handlerException(HandlerMethod handler, Exception e) {
    public Object handlerException(HandlerMethod handler, Exception e, HttpServletRequest request) {
        e.printStackTrace();
        if (useAlt(request)) {
            return altError("500", "服务器内部错误");
        }
        return R.error();
    }
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
    public Object handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e,
            HttpServletRequest request) {
        if (useAlt(request)) {
            return altError("405", "HTTP方法不支持");
        }
        return R.error();
    }
    @ExceptionHandler(CoolException.class)
    public R handleRRException(CoolException e) {
        return R.parse(e.getMessage());
    public Object handleRRException(CoolException e, HttpServletRequest request) {
        if (useAlt(request)) {
            String[] split = e.getMessage().split("-");
            String code = null;
            String msg = e.getMessage();
            if (split.length == 2 && String.valueOf(split[0]).length() < 3) {
                code = split[0];
                msg = split[1];
            }
            return altError(code, msg);
        }
        String[] split = e.getMessage().split("-");
        if (split.length == 2) {
            if (String.valueOf(split[0]).length() < 3) {
                return R.parse(e.getMessage());
            }
        }
        return R.error(e.getMessage());
    }
    private boolean useAlt(HttpServletRequest request) {
        if (null == request) {
            return false;
        }
        String header = request.getHeader("X-Response-Format");
        if ("alt".equalsIgnoreCase(header)) {
            return true;
        }
        String param = request.getParameter("responseFormat");
        return "alt".equalsIgnoreCase(param);
    }
    private Map<String, Object> altError(String code, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        if (null != code) {
            map.put("code", code);
        } else {
            map.put("code", "200");
        }
        map.put("message", "失败");
        map.put("returnMessage", message);
        map.put("timestamp", System.currentTimeMillis());
        return map;
    }
}