api中如何定义接口是合理的?抛出异常或返回ErrorCodeBean结果?

时间:2017-03-20 05:21:21

标签: java api interface

如何在api中定义接口是否合理?抛出异常或返回ErrorCodeBean结果?以下是示例:

1.1界面

Dto checkAndSetInfoForApply(String domain, String orderNo); 

1.2 Dto

public class GroupBuyProductResultDto implements Serializable {
      private static final long serialVersionUID = 7942969338660852183L;
      private Integer personNum;// 部分选中时必须人数
      private ResultTypeEnum resultTypeEnum;//接口返回类型
      private String  msg;//接口返回信息

}

1.3 ResultTypeEnum

public enum ResultTypeEnum {
SUCCESS(1,"成功"),
FAIL(2,"失败"),
EXCEPTION(3,"接口异常"),
EXT(4,"扩展");

private int code;
private String desc;

ResultTypeEnum(int code, String desc){
    this.code = code;
    this.desc = desc;
}

}

1.4转移

Dto groupBuyDto = coreservGrouBuyProductService.checkAndSetInfoForApply(domain, orderNo);
    ResultTypeEnum resultTypeEnum = groupBuyDto.getResultTypeEnum();
    switch (resultTypeEnum) {
        case EXCEPTION:
            throw new GroupBuyException("interface error");
        case FAIL:
            break;
        case SUCCESS:
           do somthing...
        default:
            break;
    }

2.1界面

Dto checkAndSetInfoForApply(String domain, String orderNo) throws Exception;

2.2 Dto

public class GroupBuyProductResultDto implements Serializable {
  private static final long serialVersionUID = 7942969338660852183L;
  private Integer personNum;// 部分选中时必须人数

2.3转移

try{
        Dto groupBuyDto = coreservGrouBuyProductService.checkAndSetInfoForApply(domain, orderNo);
    }catch(Exception e){
        wrong...
    }

哪种方式更合适(1或2)?

1 个答案:

答案 0 :(得分:0)

在你的场景中第二个工具更好,推荐的方法是从服务返回一个dto或异常dto到控制器,你应该为所有异常定义统一的异常处理控制器,你可以引用spring-boot的代码&# 39; s异常处理程序。 示例如下所示,

@ControllerAdvice(annotations = RestController.class)   公共类RestExceptionHandler {

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

@ExceptionHandler
@ResponseBody
//@ResponseStatus(HttpStatus.BAD_REQUEST)
private RestResult runtimeExceptionHandler(Exception ex) {
    LOGGER.error("---------> error!", ex);
    return RestResultBuilder.builder().failure().build();
}

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
//@ResponseStatus(HttpStatus.BAD_REQUEST)
private RestResult     illegalParamsExceptionHandler(MethodArgumentNotValidException ex) {
    BindingResult bindingResult = ex.getBindingResult();
    Map<String, String> errors = Maps.newHashMapWithExpectedSize(bindingResult
            .getFieldErrorCount());
    for (FieldError fieldError : bindingResult.getFieldErrors()) {
        errors.put(fieldError.getField(), fieldError.getDefaultMessage());
    }
    LOGGER.warn("---------> invalid request! fields ex:{}", JSON.toJSONString(errors));
    return RestResultBuilder.builder().errorCode(GlobalErrorCode.BAD_REQUEST).data
            (errors).build();
}

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
//@ResponseStatus(HttpStatus.BAD_REQUEST)
public RestResult messageNotReadableExceptionHandler(HttpMessageNotReadableException ex) {
    LOGGER.warn("---------> json convert failure, exception:{}", ex.getMessage());
    return RestResultBuilder.builder().errorCode(GlobalErrorCode.BAD_REQUEST).build();
}

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
//@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public RestResult methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException ex) {
    LOGGER.error("---------> path variable, exception:{}", ex.getMessage());
    return RestResultBuilder.builder().errorCode(GlobalErrorCode.BAD_REQUEST).message(ex.getMessage()).build();
}

}