Unified encapsulation of response results

Time:2021-2-20
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.*;

/**
 *Used to use {@ link} to return the controller value com.fansunion.cloud . commons.RestResult }Package
 *
 * @author youmoo
 * @since 16/3/31 16:08
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RestWrapper {

    /**
     *Package to result field
     * <p>
     *Originally:
     * [1,2,3]
     * <p>
     *After package:
     * {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 (null pointer, e);
        RestResult<Void> res = new RestResult<>();

        res.setStatus(RestStatus.PARAM_INVALID.value());
        res.setMessage ("null pointer, please contact technology");

        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 (), "system busy, please try again later");
    }

    @ResponseBody
    @ExceptionHandler({Exception.class})
    public RestResult<Void> errorHandler(Exception e, HttpServletRequest request) {
        log.error ("server exception.", 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 (), "system busy, please try again later");
    }
}

Recommended Today

Redis design and implementation 4: Dictionary Dict

In redis, the dictionary is the infrastructure. Redis database data, expiration time and hash type all take the dictionary as the underlying structure. Structure of dictionary Hashtable The implementation code of hash table is as follows:dict.h/dictht The dictionary of redis is implemented in the form of hash table. typedef struct dictht { //Hash table array, […]