响应结果统一封装


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 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字段中
     * 

* 原本: * [1,2,3] *

* 包裹后: * {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 handle(IllegalArgumentException e) { RestResult res = new RestResult<>(); res.setStatus(RestStatus.PARAM_INVALID.value()); res.setMessage(e.getMessage()); return res; } @ExceptionHandler(NullPointerException.class) public RestResult handle(NullPointerException e, HttpServletRequest request) { log.error("空指针", e); RestResult 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 handle(ServiceException e, HttpServletRequest request) { RestResult 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 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 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(), "系统繁忙,请稍后重试"); } }

你可能感兴趣的:(java,spring)