java 如何通过Swagger注解获取自定义错误代码

ovfsdjhp  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(329)
*`I have below schema definition to represent commission amount in my openapi contract.`*

"properties": {
        "Amount": {
          "type": "number",
          "description": "The amount of tnx",
          "pattern" : "^-?[0-9]*(\\.([0-9]{1,2}))?$",
          "format": "big-decimal",
          "minimum": 0.01,
          "maximum": 49999.99,
          "exclusiveMinimum": false,
          "exclusiveMaximum": false,
          "example" : "9999.99"
        },

生成代码:

@NotNull @Valid @DecimalMin("0.01") @DecimalMax("49999.99") 
  @Schema(name = "amount", example = "9999.99", description = "The amount of tnx", required = true)
  public BigDecimal getAmount() {
    return amount;
  }
  • 当我给出高于50000或低于0.01时,它会通过 Postman 给出正确的验证消息 *
{
    "errors": [
        {
            "code": "DecimalMax",
            "message": "must be less than or equal to 49999.99",
            "field": "Amount"
        }
    ]
}

{
    "errors": [
        {
            "code": "DecimalMin",
            "message": "must be greater than or equal to 0.01",
            "field": "Amount"
        }
    ]
}

but i want override the code with some some number to represent the error code like 100,101 etc

{
    "errors": [
        {
            "code": "100",
            "message": "must be less than or equal to 49999.99",
            "field": "Amount"
        }
    ]
}

{
    "errors": [
        {
            "code": "101",
            "message": "must be greater than or equal to 0.01",
            "field": "Amount"
        }
    ]
}

can i specify any annotation on swagger to achieve this
kknvjkwl

kknvjkwl1#

默认情况下,当字段验证失败时,Spring将抛出MethodArgumentNotValidException。这由Springs spring-boot-starter-validation内部管理。您可以使用@RestControllerAdvice@ControllerAdvice覆盖此异常处理。
首先,为你的React建立一个基本模型,这是一个非常简单的模型。

@Setter
@Getter
public class RestException {
  String code;
  String message;
}

然后,创建控制器通知类。

@RestControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

  @Override
  protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

    RestException exception = new RestException();
    exception.setCode(HttpStatus.BAD_REQUEST.toString());
    var message = Optional.ofNullable(ex).map(MethodArgumentNotValidException::getBindingResult).map(BindingResult::getFieldError).orElse(null);

    exception.setMessage(Objects.isNull(message) ? "unidentified error" : message.getField() + " " + message.getDefaultMessage());

    return new ResponseEntity<>(exception, HttpStatus.BAD_REQUEST);
  }
}

这个非常简单的示例将返回以下响应

{
  "code": "400 BAD_REQUEST",
  "message": "amount must be greater than or equal to 0"
}

备注

你可以随意设置返回给用户的代码(也就是exception.setCode(“99999MY_STATUS_CODE”))。但是,这对用户没有任何意义,因为它与控制器发送的作为ResponseEntity一部分的头不匹配。我建议坚持使用定义的HttpStatus类型作为返回给用户的代码。
另外,除非你特别想得到一个BigDecimal作为你的类型,将数字的格式设置为floatdouble将得到预期的dataType,否则,声明big-decimal是不必要的,因为这是没有定义格式的number的默认值。
同样,exclusiveMinimumexclusiveMaximum的缺省值默认为false,因此不需要将它们包含在模式中。
最后,我建议调整您的模式以包含响应描述。

responses:
  "200":
    description: OK
  "5XX":
    description: Unknown error has occurred
  "400":
    description: A required parameter is missing or an invalid datatype or value was provided for property.  
      Check the error message to check the invalid information, adjust the provided schema, and try again.

这应该涵盖了所有的基础。请随意扩展RestExceptionRestExceptionHandler类。正如我所说的,这些是基本的示例。您可以使它们更加健壮(即基于字段或错误消息的多个返回)。

相关问题