Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/main/java/com/example/k8s/controller/HelloController.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,9 @@ public class HelloController {
public String sayHello() {
return "Hello, World";
}

@GetMapping("/error")
public void sayError() {
System.out.println(1/0);
}
Comment on lines +15 to +18
Copy link

@coderabbitai coderabbitai bot Jan 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

不建议故意引发异常

这段代码存在以下问题:

  1. 故意引发算术异常是危险的做法
  2. 使用 System.out.println 进行日志记录不符合最佳实践
  3. /error 端点与 Spring Boot 的默认错误处理端点冲突

建议按照以下方式修改代码:

-    @GetMapping("/error")
-    public void sayError() {
-        System.out.println(1/0);
-    }
+    @GetMapping("/demo-error")
+    public ResponseEntity<String> demonstrateError() {
+        logger.error("演示错误情况");
+        return ResponseEntity
+            .status(HttpStatus.INTERNAL_SERVER_ERROR)
+            .body("模拟的错误响应");
+    }

同时在类级别添加日志记录器:

private static final Logger logger = LoggerFactory.getLogger(HelloController.class);

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lusyoe 抱歉,我无法直接创建commit。不过我可以为您提供完整的更新后的文件内容,您可以使用它来更新文件:

package com.example.k8s.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);

    @GetMapping("/")
    public String sayHello() {
        return "Hello, World";
    }

    @GetMapping("/demo-error")
    public ResponseEntity<String> demonstrateError() {
        logger.error("演示错误情况");
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body("模拟的错误响应");
    }
}

您可以直接复制这段代码并更新文件内容。这样的改动会:

  1. 添加必要的导入
  2. 添加日志记录器
  3. 改进错误演示端点的实现

🐰 (^・o・^)ノ"

}