springboot配置公共返回异常和http切面 (配置记录)

结果返回类:


@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class ApiResultVO {

    public Object getPage() {
        return page;
    }

    public ApiResultVO setPage(Object page) {
        this.page = page;
        return this;
    }

    public static enum ApiResultCode{
        ERR_SYSTEM(301),
        ERR_AUTH(311),
        ERR_PARAM(321),
        ERR_OPERATION(331),
        ERR_HTTPREQ(341),
        ERR_DATABASE(351),
        SUCCESS(200);

        private int code;
        ApiResultCode(int code){
            this.code = code;
        }

        public int code(){
            return code;
        }
    }

    private int code;
    private String message;
    private Object data;
    private Object page;

    private ApiResultVO(){

    }


    public ApiResultVO(int code){
        this.code = code;
    }

    public ApiResultVO(int code , String messgae){
        this.code = code;
        this.message = messgae;
    }

    public static ApiResultVO getSuccessInstance(){
        return new ApiResultVO(ApiResultCode.SUCCESS.code());
    }

    public ApiResultVO data(Object data){
        this.data = data;

        if(data instanceof Page){
            this.page = parsePage((Page)data);
        }

        return this;
    }

    public static Map parsePage(Page page){
        Map pageMap = new HashMap<>();
        pageMap.put("page_num" , page.getPageNum());
        pageMap.put("pages" , page.getPages());
        pageMap.put("page_size" , page.getPageSize());
        pageMap.put("total" , page.getTotal());
        return pageMap;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ApiResultVO{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                ", page=" + page +
                '}';
    }
}

自定义异常类:

public class PyException extends Exception {
    private ApiResultVO.ApiResultCode code;
    private String message;
    private Boolean logflag = false;
    private Object debug;

    public PyException(ApiResultCode code) {
        this.code = code;
    }

    public PyException(ApiResultCode code , String message) {
        this.code = code;
        this.message = message;
    }

    public PyException(ApiResultCode code , String message , Boolean logflag) {
        this.code = code;
        this.message = message;
        this.logflag = logflag;
    }

    public PyException(ApiResultCode code , String message , Object debug) {
        this.code = code;
        this.message = message;
        this.debug = debug;
    }

    public PyException(ApiResultCode code , String message , Boolean logflag , Object debug) {
        this.code = code;
        this.message = message;
        this.logflag = logflag;
        this.debug = debug;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public ApiResultCode getCode() {
        return code;
    }

    public void setCode(ApiResultCode code) {
        this.code = code;
    }

    public Boolean getLogflag() {
        return logflag;
    }

    public void setLogflag(Boolean logflag) {
        this.logflag = logflag;
    }

    public Object getDebug() {
        return debug;
    }

    public void setDebug(Object debug) {
        this.debug = debug;
    }
}

异常捕获类:

@RestControllerAdvice
public class CommonExceptionHandle {

    protected Logger logger= Logger.getLogger(getClass());

    @ExceptionHandler(value = PyException.class)
    @ResponseBody()
    public ApiResultVO defaultHandle(PyException e) throws IOException {

        if(e.getLogflag()){
            logger.error("自定义错误处理" , e);
        }

        if(e.getDebug() != null){
            logger.debug(e.getDebug());
        }

        ApiResultVO apiResultVO = new ApiResultVO(e.getCode().code() , e.getMessage());

        return apiResultVO;
    }
}

引入aspect依赖:

  
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
        dependency>

配置httpAspect对控制器切面:

@Aspect
@Component
public class HttpAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);

    private long totalTime = 0;
    @Autowired
    private CommonExceptionHandle commonExceptionHandle;

    @Pointcut("execution(public * com.item1024.controller.*.*(..))")
    public void log(){

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        totalTime = System.currentTimeMillis();
        //url
        LOGGER.info("url={}",request.getRequestURL());
        //method
        LOGGER.info("method={}",request.getMethod());
        //ip
        LOGGER.info("id={}",request.getRemoteAddr());
        //class_method
        LOGGER.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName() + "," + joinPoint.getSignature().getName());
        //args[]
        LOGGER.info("args={}",joinPoint.getArgs());
    }

    @Around("log()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Result result = null;
        try {

        } catch (Exception e) {
            return commonExceptionHandle.defaultHandle((PyException)e);
        }
        if(result == null){
            return proceedingJoinPoint.proceed();
        }else {
            return result;
        }
    }

    @AfterReturning(pointcut = "log()",returning = "object")//打印输出结果
    public void doAfterReturing(Object object){
        LOGGER.info("sendTime={}",System.currentTimeMillis() - totalTime);
        LOGGER.info("response={}",object.toString());
    }

测试:

    @GetMapping("/testException")
    public ApiResultVO test(int id) throws PyException {
        if (id == 1)
            throw new PyException(ApiResultVO.ApiResultCode.ERR_AUTH, "错误");

        return ApiResultVO.getSuccessInstance().data("aaaaaa");
    }

结果:

: url=http://localhost:1527/billstock/bill/list
: method=GET
: id=0:0:0:0:0:0:0:1
: class_method=com.item1024.controller.BillController,list
: args=aada960d-2578-4dbb-ad42-f989fe61e4e4
: sendTime=86
: response=ApiResultVO{code=200, message='null', data={"list":[{json数据}],"total":{"count":3,"amount":"400000.00"}}, page={total=3, pages=1, page_num=1, page_size=10}}

spring 可以直接把注解切面改为注入的方式即可

 
    
    
    <bean id="httpAspect" class="com.item1024.aspects.HttpAspect"/>
    <aop:config>
        <aop:aspect id="exParamAspect" ref="httpAspect">
            <aop:pointcut id="exParam" expression="execution(* com.item1024.controller.*.*(..))" />
            <aop:before method="doBefore" pointcut-ref="exParam"/>
            <aop:around method="doAround" pointcut-ref="exParam"/>
            <aop:after-returning pointcut-ref="exParam" method="doAfterReturing"  returning="object"/>
        aop:aspect>
    aop:config>

你可能感兴趣的:(java)