在Spring Boot中处理openapi的异常:”3.0.2″

huangapple 未分类评论48阅读模式
英文:

Exception Handling in Springboot with openapi: "3.0.2"

问题

# yml文件

/namespace/{namespace}/bucket/{bucketName}/file/{fileName}:
  get:
    operationId: downloadFileFromEcs
    summary: 从ECS下载文件
    description: 从ECS下载文件
    security:
      - x-et-auth-details: []
    tags:
      - ECS
    parameters:
      - in: path
        name: bucketName
        schema:
          type: string
          required: true
      - in: path
        name: namespace
        schema:
          type: string
          required: true
      - in: path
        name: fileName
        schema:
          type: string
          required: true
    responses:
      200:
        description: 下载文件成功
        content:
          application/octet-stream:
            schema:
              $ref: "#/components/schemas/DownloadFile"
      400:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Error400BadRequest"
      403:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Error403AccessDenied"
      404:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Error404NotFound"
      500:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Error500InternalServerError"
      default:
        description: 非预期错误
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ErrorResponse"
// Rest-api.java

@ApiOperation(
  value = "从ECS下载文件",
  nickname = "downloadFileFromEcs",
  notes = "从ECS下载文件",
  response = org.springframework.core.io.Resource.class,
  tags = { "ECS" })
@ApiResponses(value = {
  @ApiResponse(code = 200, message = "下载文件成功", response = org.springframework.core.io.Resource.class),
  @ApiResponse(code = 400, message = "", response = Error400BadRequest.class),
  @ApiResponse(code = 403, message = "", response = Error403AccessDenied.class),
  @ApiResponse(code = 404, message = "", response = Error404NotFound.class),
  @ApiResponse(code = 500, message = "", response = Error500InternalServerError.class),
  @ApiResponse(code = 200, message = "非预期错误", response = ErrorResponse.class)
})
@RequestMapping(
  value = "/namespace/{namespace}/bucket/{bucketName}/file/{fileName}",
  produces = { "application/octet-stream", "application/json" },
  method = RequestMethod.GET)
default CompletableFuture<ResponseEntity<org.springframework.core.io.Resource>> _downloadFileFromEcs(
  @ApiParam(value = "", required = true) @PathVariable("bucketName") String bucketName,
  @ApiParam(value = "", required = true) @PathVariable("namespace") String namespace,
  @ApiParam(value = "", required = true) @PathVariable("fileName") String fileName
) {
  return downloadFileFromEcs(bucketName, namespace, fileName);
}
// Rest-impl.java

@Override
public CompletableFuture<ResponseEntity<Resource>> downloadFileFromEcs(String bucketName, String namespace, String fileName) {
  // 将文件加载为资源
  logger.info("[ECS Controller] 下载:开始输入流");
  InputStream inputStream = ecsService.downloadFileFromS3Bucket(bucketName, namespace, fileName);
  logger.info("[ECS Controller] 下载:开始资源");

  Resource resource = new InputStreamResource(inputStream);
  logger.info("[ECS Controller] 设置文件下载响应");
  String contentType = "application/octet-stream";
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setContentType(MediaType.parseMediaType(contentType));
  logger.info("[ECS Controller] 设置HTTP头");

  return CompletableFuture.completedFuture(new ResponseEntity<Resource>(
    resource, httpHeaders, HttpStatus.OK));
}
// ServiceIMPL.java

public InputStream downloadFileFromS3Bucket(String bucket, String namespace, String fileName) throws AmazonS3Exception {
  if (!namespace.isEmpty() && namespace.equals("ac_gemsync")) {
    accessKey = accessKeyGem;
    secretKey = secretKeyGem;
  }
  if (!bucket.isEmpty()) {
    bucketName = bucket;
  }
  String result = "";
  AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
  AmazonS3Client s3client = new AmazonS3Client(credentials);
  s3client.setEndpoint(endpointUrl);
  S3ClientOptions options = new S3ClientOptions();
  options.setPathStyleAccess(true);
  s3client.setS3ClientOptions(options);
  logger.info("[ECS Download] 下载:开始S3下载");
  long startTime = System.currentTimeMillis();
  S3Object object = s3client.getObject(new GetObjectRequest(bucketName, fileName));
  long endTime = System.currentTimeMillis();
  long totalTime = endTime - startTime;
  logger.info("[ECS CALL] downloadFileFromS3Bucket: :" + totalTime + " 毫秒");
  logger.info("[ECS Download] 下载:开始输入流");
  InputStream inputStream = object.getObjectContent();
  logger.info("[ECS Download] 完成输入流");

  return inputStream;
}
英文:

I am trying to handle exceptions within my downloadfile Api. I am using openapi: "3.0.2" in springboot service. I tried implementing controlleradvice but OPEN API is not supporting Controlleradvice. Could you please suggest a standard approach or soulution which helps me in handling exceptions.
Please find my delete file code below.

yml file

/namespace/{namespace}/bucket/{bucketName}/file/{fileName}:

get:
  operationId: downloadFileFromEcs
  summary: Download file from ECS
  description: |-
    Download file from ECS
  security:
    - x-et-auth-details: []
  tags:
    - ECS
  parameters:
    - in: path
      name: bucketName
      schema:
        type: string
        required: true
    - in: path
      name: namespace
      schema:
        type: string
        required: true
    - in: path
      name: fileName
      schema:
        type: string
        required: true

  responses:
    200:
      description: Downloaded file
      content:
        application/octet-stream:
          schema:
            $ref: &quot;#/components/schemas/DownloadFile&quot;
    400:
      content:
        application/json:
          schema:
            $ref: &quot;#/components/schemas/Error400BadRequest&quot;
    403:
      content:
        application/json:
          schema:
            $ref: &quot;#/components/schemas/Error403AccessDenied&quot;
    404:
      content:
        application/json:
          schema:
            $ref: &quot;#/components/schemas/Error404NotFound&quot;
    500:
      content:
        application/json:
          schema:
            $ref: &quot;#/components/schemas/Error500InternalServerError&quot;
    default:
      description: unexpected error
      content:
        application/json:
          schema:
            $ref: &quot;#/components/schemas/ErrorResponse&quot;

Rest-api.java

 @ApiOperation(value = &quot;Download file from ECS&quot;, nickname = &quot;downloadFileFromEcs&quot;, notes = &quot;Download file from ECS&quot;, response = org.springframework.core.io.Resource.class, tags={ &quot;ECS&quot;, })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = &quot;Downloaded file&quot;, response = org.springframework.core.io.Resource.class),
    @ApiResponse(code = 400, message = &quot;&quot;, response = Error400BadRequest.class),
    @ApiResponse(code = 403, message = &quot;&quot;, response = Error403AccessDenied.class),
    @ApiResponse(code = 404, message = &quot;&quot;, response = Error404NotFound.class),
    @ApiResponse(code = 500, message = &quot;&quot;, response = Error500InternalServerError.class),
    @ApiResponse(code = 200, message = &quot;unexpected error&quot;, response = ErrorResponse.class) })
@RequestMapping(value = &quot;/namespace/{namespace}/bucket/{bucketName}/file/{fileName}&quot;,
    produces = { &quot;application/octet-stream&quot;, &quot;application/json&quot; }, 
    method = RequestMethod.GET)
default CompletableFuture&lt;ResponseEntity&lt;org.springframework.core.io.Resource&gt;&gt; _downloadFileFromEcs(@ApiParam(value = &quot;&quot;,required=true) @PathVariable(&quot;bucketName&quot;) String bucketName
,@ApiParam(value = &quot;&quot;,required=true) @PathVariable(&quot;namespace&quot;) String namespace
,@ApiParam(value = &quot;&quot;,required=true) @PathVariable(&quot;fileName&quot;) String fileName
) {
        return downloadFileFromEcs(bucketName, namespace, fileName);
    }

// Override this method
default CompletableFuture&lt;ResponseEntity&lt;org.springframework.core.io.Resource&gt;&gt; downloadFileFromEcs(String bucketName,String namespace,String fileName) {
    if(getObjectMapper().isPresent() &amp;&amp; getAcceptHeader().isPresent()) {
        if (getAcceptHeader().get().contains(&quot;application/json&quot;)) {
            try {
                return CompletableFuture.completedFuture(new ResponseEntity&lt;&gt;(getObjectMapper().get().readValue(&quot;\&quot;\&quot;&quot;, org.springframework.core.io.Resource.class), HttpStatus.NOT_IMPLEMENTED));
            } catch (IOException e) {
                log.error(&quot;Couldn&#39;t serialize response for content type application/json&quot;, e);
                return CompletableFuture.completedFuture(new ResponseEntity&lt;&gt;(HttpStatus.INTERNAL_SERVER_ERROR));
            }
        }
    } else {
        log.warn(&quot;ObjectMapper or HttpServletRequest not configured in default EcsApi interface so no example is generated&quot;);
    }
    return CompletableFuture.completedFuture(new ResponseEntity&lt;&gt;(HttpStatus.NOT_IMPLEMENTED));
}

Rest-impl.java

 @Override
public CompletableFuture&lt;ResponseEntity&lt;Resource&gt;&gt; downloadFileFromEcs(String bucketName,String namespace, String fileName) {
    // Load file as Resource
    logger.info(&quot;[ECS Controller] Download: Starting input stream&quot;);
    InputStream inputStream = ecsService.downloadFileFromS3Bucket(bucketName, namespace, fileName);
    logger.info(&quot;[ECS Controller] Download: Starting resource &quot;);

    Resource resource = new InputStreamResource(inputStream);
    logger.info(&quot;[ECS Controller] setting fileDownloadResponse&quot;);
    String contentType = &quot;application/octet-stream&quot;;
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.parseMediaType(contentType));
    logger.info(&quot;[ECS Controller] setting http headers&quot;);

/*        return CompletableFuture.completedFuture(ResponseEntity&lt;ECSDownloadResponse&gt;.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, &quot;attachment; filename=\&quot;&quot; + fileName + &quot;\&quot;&quot;)
                .body(resource));*/
        return CompletableFuture.completedFuture(new ResponseEntity&lt;Resource&gt;(
                resource,httpHeaders, HttpStatus.OK));
    }

ServiceIMPL.java

  public InputStream downloadFileFromS3Bucket(String bucket, String namespace, String fileName) throws AmazonS3Exception {
        if (!namespace.isEmpty() &amp;&amp; namespace.equals(&quot;ac_gemsync&quot;)) {
            accessKey = accessKeyGem;
            secretKey = secretKeyGem;
        }
        if (!bucket.isEmpty()) {
            bucketName = bucket;
        }
        String result = &quot;&quot;;
        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AmazonS3Client  s3client = new AmazonS3Client(credentials);
        s3client.setEndpoint(endpointUrl);
        S3ClientOptions options = new S3ClientOptions();
        options.setPathStyleAccess(true);
        s3client.setS3ClientOptions(options);
        logger.info(&quot;[ECS Download] Download: Starting s3 download&quot;);
        long startTime = System.currentTimeMillis();
        S3Object object = s3client.getObject(new GetObjectRequest(bucketName, fileName));
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        logger.info(&quot;[ECS CALL] downloadFileFromS3Bucket: :&quot; + totalTime + &quot; milli secs&quot;);
        logger.info(&quot;[ECS Download] Download: Starting input stream&quot;);
        InputStream inputStream = object.getObjectContent();
        logger.info(&quot;[ECS Download] Done input stream&quot;);

    return inputStream;
}

huangapple
  • 本文由 发表于 2020年5月30日 05:35:58
  • 转载请务必保留本文链接:https://java.coder-hub.com/62094911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定