简体   繁体   中英

Is there a way to reference response in swagger @ApiResponse from json or yml rather than a class?

I have the following annotation used in a controller:

@ApiResponse(code = 400, message = "failed", response = MediaDataProductResponseV2.class)}

As you can see, the response string is displayed based on the class. How can you reference the response from a file like yml or json?

example

@ApiResponse(code = 400, message = "failed", response = "${error}")} -> this doesn't work

The problem I have is that the company's code is including all the error and success objects in a single pojo so there is no way to segregate the type of response we send to our clients. Let's say we have the following pojo response:

public class pojo{
       private String error;
       private String response;
       … setters and getters...
    }
    

If something goes wrong we just return the error part. If success, the response. There is no way I can point that out in the annotations as it will always serialize the whole thing and I don't want to play around with the pojos as they they are generated from a json schema. I need to reference the response from something else that can't be a class.

Error-handling is a cross-cutting concern and hence should not be tangled with business logic. Therefore It would be better to have a seperate class annotated with @ControllerAdvice that handles failures.

You then define a method that takes the exception and a HttpServletRequest as parameters and returns a ResponseEntity of a type that contains the error message you want to return.

This method is annotated with @ExceptionHandler(myException.class) . The exception itself is annotated with @ResponseStatus(HTTPSTATUS.MYSTATUS) . That way you have centralized your error-handling in one place while at the same time applying the error handling to all your controllers.

You can override this however by passing the basePackageClasses as an argument to the @ControllerAdvice annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM