0
点赞
收藏
分享

微信扫一扫

ResponseEntity为单独接口实现灵活返回值控制

松鼠树屋 2021-09-21 阅读 21

实现

  • 项目的统一返回值协议WebResult
/**
 * @author timxia
 * @since 2019/8/13
 */
@Getter
@Setter
@ToString
@NoArgsConstructor
public class WebResult<T> {
    private static final int SUCCESS_CODE = 200;
    private static final int SERVER_ERROR_CODE = 500;

    private static final String SUCCESS_MSG = "操作成功";
    private static final String ERROR_SERVER = "服务器繁忙,请稍后再试";

    public static final WebResult<Void> SUCCESS_RESULT = new WebResult<>();
    public static final WebResult<Void> SERVER_ERROR_RESULT = new WebResult<>(SERVER_ERROR_CODE, ERROR_SERVER);

    /**
     * 错误码.
     */
    private int code = SUCCESS_CODE;

    /**
     * 错误信息.
     */
    private String msg = SUCCESS_MSG;

    /**
     * 结果内容.
     */
    private T data;

    public WebResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    
    public WebResult(T data) {
        this.data = data;
    }
}
  • 返回不同的HttpStatus
@RequestMapping("home")
@RestController
@SpringBootApplication
public class BootEntityApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootEntityApplication.class, args);
    }

    @GetMapping("ping")
    public WebResult<Void> ping() {
        return WebResult.SUCCESS_RESULT;
    }

    /**
     * 根据不同的异常情况,配置不同的HttpStatus
     */
    @GetMapping("exception")
    public ResponseEntity<WebResult> exception(int ex) {
        try {
            doWork(ex);
            return ResponseEntity.ok(WebResult.SUCCESS_RESULT);
        } catch (IllegalArgumentException e) {
            //不同的异常设置不同的HttpStatus
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new WebResult<>(400, e.getMessage()));
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(WebResult.SERVER_ERROR_RESULT);
        }
    }

    private void doWork(int ex) {
        switch (ex) {
            case 0:
                return;
            case 1:
                throw new IllegalArgumentException("bad request");
            default:
                throw new RuntimeException("服务器繁忙");
        }
    }
}

测试

# 没有异常HttpStatus=200
$ curl -i -X GET 'http://localhost:8080/home/exception?ex=0'

HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Tue, 17 Dec 2019 13:29:55 GMT

{"code":200,"msg":"操作成功","data":null,"success":true}

#参数异常HttpStatus=400
$ curl -i -X GET 'http://localhost:8080/home/exception?ex=1'

HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Tue, 17 Dec 2019 13:29:19 GMT
Connection: close

{"code":400,"msg":"bad request","data":null,"success":false}

#服务器异常HttpStatus=500
$ curl -i -X GET 'http://localhost:8080/home/exception?ex=2'

HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Tue, 17 Dec 2019 13:30:05 GMT
Connection: close

{"code":500,"msg":"服务器繁忙,请稍后再试","data":null,"success":false}

优点

  • 使用ResponseEntity可以针对单个接口实现灵活的返回值控制,包括HttpStatus
  • 如果在所有接口实现对某一个异常都设置统一的HttpStatus,可以使用ExceptionHandler
  • 使用HttpServletResponse也可以实现非常灵活的返回值控制,但是太底层了,不够面向对象,不建议使用
举报

相关推荐

0 条评论