美文网首页
springboot 九-响应结果

springboot 九-响应结果

作者: 小眼睛的露鹿酱 | 来源:发表于2022-02-18 20:42 被阅读0次

    统一响应大对象

    resultCode : 1成功 0失败
    message :提示信息
    data:json文件

    响应data 状态码 message

    涉及信息包括
    响应数据data

    package com.example.questionlist2.common;
    
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    import java.io.Serializable;
    
    @Data
    public class resultDto<T> implements Serializable {
        @ApiModelProperty(value = "响应Code,其中1表示成功 0表示失败",required = true,example = "1",allowableValues = "0")
        private Integer resultCode;
        @ApiModelProperty(value ="响应信息")
        private String message="";
        @ApiModelProperty(value = "响应数据")
        private T data=null;
    
    
        public static resultDto newResultDto(){
            return new resultDto();
        }
    
        //状态为成功  重载  函数name一致 但是参数不一样 调用的时候会区别的
        public static resultDto sucess(String msg){
            resultDto resultDto =new resultDto();
            resultDto.setMessage(msg);
            resultDto.setResultCode(1);
            return resultDto;
    
        }
    
        public static  <T> resultDto<T> sucess(String msg,T t){
            // <T> resultDto<T> 正确的返回
            //  resultDto<T> 报错
            resultDto<T> resultDto = new resultDto<>();
            resultDto.setResultCode(1);
            resultDto.setMessage(msg);
            resultDto.setData(t);
    
            return resultDto;
        }
    
    
        //状态为失败  重载  函数name一致 但是参数不一样 调用的时候会区别的
    
    
        public static resultDto fail(String msg){
            resultDto resultDto =new resultDto();
            resultDto.setMessage(msg);
            resultDto.setResultCode(0);
            return resultDto;
    
        }
    
        public static  <T> resultDto<T> fail (String msg,T t){
            // <T> resultDto<T> 正确的返回
            //  resultDto<T> 报错
            resultDto<T> resultDto = new resultDto<>();
            resultDto.setResultCode(1);
            resultDto.setMessage(msg);
            resultDto.setData(t);
            return resultDto;
        }
    }
    

    调用接口如下

    
        @PostMapping(value = "addQuestionResult")
        public resultDto addQuestionResult(@RequestBody questionDto questionDto) {
            if (questionDto.getQuestionName().contains("  ")) {
                myException.throwMyEx("questionName is not correct");
            }
            //现在去直接抛出异常
            if (questionDto.getQuestionName().contains("errorNULL")) {
                myException demo = new myException("包含null", new NullPointerException());
            }
            System.out.println(questionDto.getQuestionName() + " " + questionDto.getBook());
            return resultDto.sucess("post over\n"
                    +questionDto.getQuestionName() +"\n"
                    +questionDto.getQuestionType());
        }
    

    postman


    图片.png

    由于没有上传具体的Dto对象 所以data 为null

     @PostMapping(value = "addQuestionResult")
        public resultDto addQuestionResult(@RequestBody questionDto questionDto) {
            if (questionDto.getQuestionName().contains("  ")) {
                myException.throwMyEx("questionName is not correct");
            }
            //现在去直接抛出异常
            if (questionDto.getQuestionName().contains("errorNULL")) {
                myException demo = new myException("包含null", new NullPointerException());
            }
            System.out.println(questionDto.getQuestionName() + " " + questionDto.getBook());
    //        return resultDto.sucess("post over\n"
    //                +questionDto.getQuestionName() +"\n"
    //                +questionDto.getQuestionType());
            return resultDto.sucess("post over",questionDto);
        }
    

    postman 结果


    图片.png

    此时考虑到正常的接口响应是resultDto 那异常的时候就可以不像之前那样打印信息了, 可以也返回一个json文件

    package com.example.questionlist2.common;
    
    
    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.ResponseStatus;
    
    @ControllerAdvice  //标识这个类是一个全局异常处理的类   定义在类上
    @ResponseBody  //在相应体中使用
    public class myglobalExceptionHandle {
    
        //异常分为:业务异常和其他异常
        //业务异常
        @ExceptionHandler({myException.class})
        //统一处理value对应的异常,
        // 如果这个类的子类和父类都被声明时  先子后父的顺序捕获
        @ResponseStatus(value = HttpStatus.BAD_REQUEST)
        public resultDto serviceExphandle(myException myException){
            return commontip(myException);
        }
    
    
        //其他异常
        @ResponseStatus(value=HttpStatus.BAD_GATEWAY)
        @ExceptionHandler({Exception.class})
        public resultDto othersExphandle(Exception e){
            return commontip(e);
        }
    
        //系统异常
        @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
        @ExceptionHandler({Throwable.class})
        public resultDto systemExphandle(Throwable t){
            return commontip( t);
        }
        //发现 return的结果可以再放入一个函数中
        public resultDto commontip(Throwable t){
            String tip="请稍后查看具体原因";
            if (t instanceof myException){
                return resultDto.fail(t.getMessage()+": 业务异常",t);
            }
            if (t instanceof Exception){
                return resultDto.fail(t.getMessage()+": 其他异常",t);
            }
            if (t instanceof Throwable){
                return resultDto.fail(t.getMessage()+": 系统异常",t);
    
            }
            return resultDto.sucess("no Exception");
        }
    
    }
    
    

    请求 http://localhost:8888/addQuestionResult
    {
    "questionType":"questionType1",
    "keyword":"keyword1",
    "questionName":"dedede. ",
    "dependOnQuestion":"dependOnQuestion2",
    "book":"book1"
    }
    此时的结果竟然是

    {
        "resultCode": 1,
        "message": "questionName is not correct: 业务异常",
        "data": {
            "cause": null,
            "stackTrace": [
                {
                    "methodName": "throwMyEx",
                    "fileName": "myException.java",
                    "lineNumber": 40,
                    "className": "com.example.questionlist2.common.myException",
                    "nativeMethod": false
                },
                {
                    "methodName": "addQuestionResult",
                    "fileName": "getListController.java",
                    "lineNumber": 106,
                    "className": "com.example.questionlist2.cotroller.getListController",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke0",
                    "fileName": "NativeMethodAccessorImpl.java",
                    "lineNumber": -2,
                    "className": "sun.reflect.NativeMethodAccessorImpl",
                    "nativeMethod": true
                },
                {
                    "methodName": "invoke",
                    "fileName": "NativeMethodAccessorImpl.java",
                    "lineNumber": 62,
                    "className": "sun.reflect.NativeMethodAccessorImpl",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke",
                    "fileName": "DelegatingMethodAccessorImpl.java",
                    "lineNumber": 43,
                    "className": "sun.reflect.DelegatingMethodAccessorImpl",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke",
                    "fileName": "Method.java",
                    "lineNumber": 498,
                    "className": "java.lang.reflect.Method",
                    "nativeMethod": false
                },
                {
                    "methodName": "doInvoke",
                    "fileName": "InvocableHandlerMethod.java",
                    "lineNumber": 205,
                    "className": "org.springframework.web.method.support.InvocableHandlerMethod",
                    "nativeMethod": false
                },
                {
                    "methodName": "invokeForRequest",
                    "fileName": "InvocableHandlerMethod.java",
                    "lineNumber": 150,
                    "className": "org.springframework.web.method.support.InvocableHandlerMethod",
                    "nativeMethod": false
                },
                {
                    "methodName": "invokeAndHandle",
                    "fileName": "ServletInvocableHandlerMethod.java",
                    "lineNumber": 117,
                    "className": "org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod",
                    "nativeMethod": false
                },
                {
                    "methodName": "invokeHandlerMethod",
                    "fileName": "RequestMappingHandlerAdapter.java",
                    "lineNumber": 895,
                    "className": "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter",
                    "nativeMethod": false
                },
                {
                    "methodName": "handleInternal",
                    "fileName": "RequestMappingHandlerAdapter.java",
                    "lineNumber": 808,
                    "className": "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter",
                    "nativeMethod": false
                },
                {
                    "methodName": "handle",
                    "fileName": "AbstractHandlerMethodAdapter.java",
                    "lineNumber": 87,
                    "className": "org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter",
                    "nativeMethod": false
                },
                {
                    "methodName": "doDispatch",
                    "fileName": "DispatcherServlet.java",
                    "lineNumber": 1067,
                    "className": "org.springframework.web.servlet.DispatcherServlet",
                    "nativeMethod": false
                },
                {
                    "methodName": "doService",
                    "fileName": "DispatcherServlet.java",
                    "lineNumber": 963,
                    "className": "org.springframework.web.servlet.DispatcherServlet",
                    "nativeMethod": false
                },
                {
                    "methodName": "processRequest",
                    "fileName": "FrameworkServlet.java",
                    "lineNumber": 1006,
                    "className": "org.springframework.web.servlet.FrameworkServlet",
                    "nativeMethod": false
                },
                {
                    "methodName": "doPost",
                    "fileName": "FrameworkServlet.java",
                    "lineNumber": 909,
                    "className": "org.springframework.web.servlet.FrameworkServlet",
                    "nativeMethod": false
                },
                {
                    "methodName": "service",
                    "fileName": "HttpServlet.java",
                    "lineNumber": 681,
                    "className": "javax.servlet.http.HttpServlet",
                    "nativeMethod": false
                },
                {
                    "methodName": "service",
                    "fileName": "FrameworkServlet.java",
                    "lineNumber": 883,
                    "className": "org.springframework.web.servlet.FrameworkServlet",
                    "nativeMethod": false
                },
                {
                    "methodName": "service",
                    "fileName": "HttpServlet.java",
                    "lineNumber": 764,
                    "className": "javax.servlet.http.HttpServlet",
                    "nativeMethod": false
                },
                {
                    "methodName": "internalDoFilter",
                    "fileName": "ApplicationFilterChain.java",
                    "lineNumber": 227,
                    "className": "org.apache.catalina.core.ApplicationFilterChain",
                    "nativeMethod": false
                },
                {
                    "methodName": "doFilter",
                    "fileName": "ApplicationFilterChain.java",
                    "lineNumber": 162,
                    "className": "org.apache.catalina.core.ApplicationFilterChain",
                    "nativeMethod": false
                },
                {
                    "methodName": "doFilter",
                    "fileName": "WsFilter.java",
                    "lineNumber": 53,
                    "className": "org.apache.tomcat.websocket.server.WsFilter",
                    "nativeMethod": false
                },
                {
                    "methodName": "internalDoFilter",
                    "fileName": "ApplicationFilterChain.java",
                    "lineNumber": 189,
                    "className": "org.apache.catalina.core.ApplicationFilterChain",
                    "nativeMethod": false
                },
                {
                    "methodName": "doFilter",
                    "fileName": "ApplicationFilterChain.java",
                    "lineNumber": 162,
                    "className": "org.apache.catalina.core.ApplicationFilterChain",
                    "nativeMethod": false
                },
                {
                    "methodName": "doFilterInternal",
                    "fileName": "CharacterEncodingFilter.java",
                    "lineNumber": 201,
                    "className": "org.springframework.web.filter.CharacterEncodingFilter",
                    "nativeMethod": false
                },
                {
                    "methodName": "doFilter",
                    "fileName": "OncePerRequestFilter.java",
                    "lineNumber": 117,
                    "className": "org.springframework.web.filter.OncePerRequestFilter",
                    "nativeMethod": false
                },
                {
                    "methodName": "internalDoFilter",
                    "fileName": "ApplicationFilterChain.java",
                    "lineNumber": 189,
                    "className": "org.apache.catalina.core.ApplicationFilterChain",
                    "nativeMethod": false
                },
                {
                    "methodName": "doFilter",
                    "fileName": "ApplicationFilterChain.java",
                    "lineNumber": 162,
                    "className": "org.apache.catalina.core.ApplicationFilterChain",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke",
                    "fileName": "StandardWrapperValve.java",
                    "lineNumber": 197,
                    "className": "org.apache.catalina.core.StandardWrapperValve",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke",
                    "fileName": "StandardContextValve.java",
                    "lineNumber": 97,
                    "className": "org.apache.catalina.core.StandardContextValve",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke",
                    "fileName": "AuthenticatorBase.java",
                    "lineNumber": 540,
                    "className": "org.apache.catalina.authenticator.AuthenticatorBase",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke",
                    "fileName": "StandardHostValve.java",
                    "lineNumber": 135,
                    "className": "org.apache.catalina.core.StandardHostValve",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke",
                    "fileName": "ErrorReportValve.java",
                    "lineNumber": 92,
                    "className": "org.apache.catalina.valves.ErrorReportValve",
                    "nativeMethod": false
                },
                {
                    "methodName": "invoke",
                    "fileName": "StandardEngineValve.java",
                    "lineNumber": 78,
                    "className": "org.apache.catalina.core.StandardEngineValve",
                    "nativeMethod": false
                },
                {
                    "methodName": "service",
                    "fileName": "CoyoteAdapter.java",
                    "lineNumber": 357,
                    "className": "org.apache.catalina.connector.CoyoteAdapter",
                    "nativeMethod": false
                },
                {
                    "methodName": "service",
                    "fileName": "Http11Processor.java",
                    "lineNumber": 382,
                    "className": "org.apache.coyote.http11.Http11Processor",
                    "nativeMethod": false
                },
                {
                    "methodName": "process",
                    "fileName": "AbstractProcessorLight.java",
                    "lineNumber": 65,
                    "className": "org.apache.coyote.AbstractProcessorLight",
                    "nativeMethod": false
                },
                {
                    "methodName": "process",
                    "fileName": "AbstractProtocol.java",
                    "lineNumber": 895,
                    "className": "org.apache.coyote.AbstractProtocol$ConnectionHandler",
                    "nativeMethod": false
                },
                {
                    "methodName": "doRun",
                    "fileName": "NioEndpoint.java",
                    "lineNumber": 1732,
                    "className": "org.apache.tomcat.util.net.NioEndpoint$SocketProcessor",
                    "nativeMethod": false
                },
                {
                    "methodName": "run",
                    "fileName": "SocketProcessorBase.java",
                    "lineNumber": 49,
                    "className": "org.apache.tomcat.util.net.SocketProcessorBase",
                    "nativeMethod": false
                },
                {
                    "methodName": "runWorker",
                    "fileName": "ThreadPoolExecutor.java",
                    "lineNumber": 1191,
                    "className": "org.apache.tomcat.util.threads.ThreadPoolExecutor",
                    "nativeMethod": false
                },
                {
                    "methodName": "run",
                    "fileName": "ThreadPoolExecutor.java",
                    "lineNumber": 659,
                    "className": "org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker",
                    "nativeMethod": false
                },
                {
                    "methodName": "run",
                    "fileName": "TaskThread.java",
                    "lineNumber": 61,
                    "className": "org.apache.tomcat.util.threads.TaskThread$WrappingRunnable",
                    "nativeMethod": false
                },
                {
                    "methodName": "run",
                    "fileName": "Thread.java",
                    "lineNumber": 748,
                    "className": "java.lang.Thread",
                    "nativeMethod": false
                }
            ],
            "message": "questionName is not correct",
            "localizedMessage": "questionName is not correct",
            "suppressed": []
        }
    }
    

    分页展示list

    每页数量
    页码
    总记录数

    相关文章

      网友评论

          本文标题:springboot 九-响应结果

          本文链接:https://www.haomeiwen.com/subject/mctylrtx.html