在Linux環境下,使用Swagger進行錯誤處理和日志記錄通常涉及以下幾個步驟:
定義錯誤響應模型: 在Swagger文檔中,你可以定義錯誤響應模型,以便客戶端能夠理解服務器返回的錯誤信息。
components:
schemas:
ErrorResponse:
type: object
properties:
code:
type: integer
format: int32
message:
type: string
details:
type: array
items:
type: object
properties:
field:
type: string
message:
type: string
在控制器中處理錯誤: 在你的控制器代碼中,當發生錯誤時,返回相應的錯誤響應模型。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFoundException(ResourceNotFoundException ex) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode(HttpStatus.NOT_FOUND.value());
errorResponse.setMessage(ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
// 其他異常處理方法
}
配置Swagger以顯示錯誤響應: 確保Swagger配置能夠捕獲并顯示這些錯誤響應。
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build()
.useDefaultResponseMessages(false)
.globalResponses(HttpMethod.GET, Arrays.asList(
aResponse()
.code("404")
.description("Resource not found")
.representation(MediaType.APPLICATION_JSON)
.modelRef(new ModelRef("ErrorResponse"))
));
}
配置日志框架:
使用如Logback、Log4j2等日志框架來記錄日志。在application.properties或application.yml中配置日志級別和輸出格式。
logging.level.root=INFO
logging.level.com.example.demo=DEBUG
logging.file.name=app.log
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
在代碼中記錄日志: 在關鍵的業務邏輯和異常處理中添加日志記錄。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
public class ExampleController {
private static final Logger logger = LoggerFactory.getLogger(ExampleController.class);
@GetMapping("/example")
public ResponseEntity<String> getExample() {
logger.info("Received request to get example");
try {
// 業務邏輯
return ResponseEntity.ok("Example data");
} catch (Exception e) {
logger.error("Error processing request", e);
throw new RuntimeException("Internal server error", e);
}
}
}
配置Swagger日志: 如果你使用的是Springfox Swagger,可以在配置中啟用Swagger的日志記錄。
@Bean
public UiConfiguration uiConfig() {
return UiConfigurationBuilder.builder()
.deepLinking(true)
.displayOperationId(false)
.defaultModelsExpandDepth(1)
.defaultModelExpandDepth(1)
.defaultModelRendering(ModelRendering.EXAMPLE)
.displayRequestDuration(false)
.docExpansion(DocExpansion.NONE)
.filter(false)
.maxDisplayedTags(null)
.operationsSorter(OperationsSorter.ALPHA)
.showExtensions(false)
.tagsSorter(TagsSorter.ALPHA)
.supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
.validatorUrl(null)
.build();
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build()
.useDefaultResponseMessages(false)
.globalResponses(HttpMethod.GET, Arrays.asList(
aResponse()
.code("404")
.description("Resource not found")
.representation(MediaType.APPLICATION_JSON)
.modelRef(new ModelRef("ErrorResponse"))
))
.apiInfo(apiInfo())
.forCodeGeneration(true);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Example API")
.description("Description of your API")
.version("1.0.0")
.build();
}
通過以上步驟,你可以在Linux環境下使用Swagger進行有效的錯誤處理和日志記錄。