響應結果統一封裝

package com.fansunion.cloud.luckids.controller;

import com.fansunion.cloud.commons.RestResult;
import com.fansunion.cloud.luckids.support.RestWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class JSONResponseWrapper implements ResponseBodyAdvice {

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object returnValue, MethodParameter returnType, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (returnValue instanceof RestResult || returnValue instanceof Resource) {
            return returnValue;
        }
        RestWrapper restWrapper = returnType.getMethodAnnotation(RestWrapper.class);
        if (restWrapper == null) {
            restWrapper = returnType.getDeclaringClass().getAnnotation(RestWrapper.class);
        }
        if (restWrapper == null) {
            return returnValue;
        }
        RestResult<Object> result = new RestResult<>();
        result.setData(returnValue);

        if (returnType.getParameterType() == String.class) {
            try {
                return objectMapper.writeValueAsString(result);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return result;
    }
}


//

import java.lang.annotation.*;

/**
 * 用來將controller返回值用{@link com.fansunion.cloud.commons.RestResult}包裹
 *
 * @author youmoo
 * @since 16/3/31 16:08
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RestWrapper {

    /**
     * 是否包裹到result字段中
     * <p>
     * 本來:
     * [1,2,3]
     * <p>
     * 包裹後:
     * {result:[1,2,3]}
     */
    boolean wrapResult() default false;
}

//

package com.fansunion.cloud.luckids.controller;

import com.fansunion.cloud.commons.RestResult;
import com.fansunion.cloud.commons.RestStatus;
import com.fansunion.cloud.commons.ServiceException;
import com.fansunion.cloud.luckids.service.DingDingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;


@Slf4j
@RestControllerAdvice
public class ControllerAdvisor {

    @Autowired
    DingDingService dingDingService;

    @ExceptionHandler(IllegalArgumentException.class)
    public RestResult<Void> handle(IllegalArgumentException e) {
        RestResult<Void> res = new RestResult<>();

        res.setStatus(RestStatus.PARAM_INVALID.value());
        res.setMessage(e.getMessage());

        return res;
    }

    @ExceptionHandler(NullPointerException.class)
    public RestResult<Void> handle(NullPointerException e, HttpServletRequest request) {
        log.error("空指針", e);
        RestResult<Void> res = new RestResult<>();

        res.setStatus(RestStatus.PARAM_INVALID.value());
        res.setMessage("空指針,請聯繫技術");

        dingDingService.newContext(e)
                .add("request", request.getMethod() + " " + request.getRequestURI())
                .addDefault()
                .run();

        return res;
    }

    @ExceptionHandler({ServiceException.class})
    public RestResult<Void> handle(ServiceException e, HttpServletRequest request) {

        RestResult<Void> res = new RestResult<>();

        res.setStatus(e.getStatus());
        res.setMessage(e.getMessage());

        if (e.isReport()) {
            dingDingService.newContext(e)
                    .add("request", request.getMethod() + " " + request.getRequestURI())
                    .add("err code", e.getStatus() + "")
                    .addDefault()
                    .run();
        }

        return res;
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public RestResult<Void> handle(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {


        dingDingService.newContext(e)
                .add("request", request.getMethod() + " " + request.getRequestURI())
                .add("err code", RestStatus.SYSTEM_ERROR.value() + "")
                .add("supported methods: ", Arrays.toString(e.getSupportedMethods()))
                .addDefault()
                .run();

        return RestResult.FAIL(RestStatus.SYSTEM_ERROR.value(), "系統繁忙,請稍後重試");
    }

    @ResponseBody
    @ExceptionHandler({Exception.class})
    public RestResult<Void> errorHandler(Exception e, HttpServletRequest request) {
        log.error("服務器異常.", e);

        dingDingService.newContext(e)
                .add("request", request.getMethod() + " " + request.getRequestURI())
                .add("err code", RestStatus.SYSTEM_ERROR.value() + "")
                .addDefault()
                .run();
        return RestResult.FAIL(RestStatus.SYSTEM_ERROR.value(), "系統繁忙,請稍後重試");
    }
}
相關文章
相關標籤/搜索