HTTP Status และ ResponseEntity ใน WebFlux

Sharing is caring!

ในการพัฒนา REST API ด้วย Spring WebFlux การจัดการ HTTP Status และการส่ง response ที่เหมาะสมให้กับ client ถือเป็นหัวใจสำคัญในการทำให้ API สื่อสารอย่างเข้าใจง่าย และสามารถจัดการ error หรือผลลัพธ์ต่าง ๆ ได้อย่างมีประสิทธิภาพ บทความนี้จะพาคุณไปรู้จักกับการใช้งาน HTTP Status Codes และ ResponseEntity รวมถึง ServerResponse ใน WebFlux

ภาพหน้าปก

HTTP Status Code คืออะไร?

HTTP Status คือรหัสที่ใช้บอกผลลัพธ์ของการเรียก API เช่น 200 OK, 404 Not Found, 500 Internal Server Error เป็นต้น โดยทั่วไปแบ่งเป็นกลุ่มดังนี้:

  • 1xx – Informational
  • 2xx – Success
  • 3xx – Redirection
  • 4xx – Client Error
  • 5xx – Server Error

การใช้งาน ResponseEntity ใน @RestController

หากคุณใช้ Spring WebFlux แบบ annotation (เช่น @RestController) คุณสามารถใช้ ResponseEntity ได้เช่นเดียวกับ Spring MVC

ตัวอย่าง 200 OK

@GetMapping("/user/{id}")
public Mono<ResponseEntity<User>> getUser(@PathVariable String id) {
  return userService.findById(id)
      .map(user -> ResponseEntity.ok(user))
      .defaultIfEmpty(ResponseEntity.notFound().build());
}
  

ตัวอย่าง 201 Created

@PostMapping("/user")
public Mono<ResponseEntity<User>> createUser(@RequestBody User user) {
  return userService.save(user)
      .map(savedUser -> ResponseEntity.status(HttpStatus.CREATED).body(savedUser));
}
  

ตัวอย่าง 400 Bad Request

@GetMapping("/divide")
public Mono<ResponseEntity<String>> divide(@RequestParam int a, @RequestParam int b) {
  if (b == 0) {
    return Mono.just(ResponseEntity.badRequest().body("Division by zero is not allowed"));
  }
  return Mono.just(ResponseEntity.ok("Result = " + (a / b)));
}
  

ภาพประกอบ: HTTP Status ที่ใช้บ่อยใน REST API

การใช้งาน ServerResponse ใน Router Function

ถ้าใช้ WebFlux แบบ Functional คุณจะใช้ ServerResponse แทน ResponseEntity

ตัวอย่าง 200 OK

public Mono<ServerResponse> getUser(ServerRequest request) {
  String id = request.pathVariable("id");
  return userService.findById(id)
      .flatMap(user -> ServerResponse.ok().bodyValue(user))
      .switchIfEmpty(ServerResponse.notFound().build());
}
  

ตัวอย่าง 400 และ 500

public Mono<ServerResponse> riskyOperation(ServerRequest request) {
  try {
    int result = doSomethingRisky();
    return ServerResponse.ok().bodyValue(result);
  } catch (IllegalArgumentException e) {
    return ServerResponse.badRequest().bodyValue("Invalid input");
  } catch (Exception e) {
    return ServerResponse.status(500).bodyValue("Unexpected error");
  }
}
  

เทคนิคการจัดการ Error Response แบบ Reactive

  • ใช้ .onErrorResume() เพื่อ map error เป็น response ที่เหมาะสม
  • ใช้ WebExceptionHandler หรือ @ControllerAdvice สำหรับ global error handling

ตัวอย่าง onErrorResume

@GetMapping("/error-prone")
public Mono<ResponseEntity<String>> call() {
  return riskyMonoCall()
      .map(data -> ResponseEntity.ok(data))
      .onErrorResume(e -> Mono.just(ResponseEntity.status(500).body("Fail: " + e.getMessage())));
}
  

สรุป

Spring WebFlux รองรับการจัดการ HTTP Status ได้อย่างครบถ้วน ไม่ว่าจะใช้ในรูปแบบ declarative (@RestController) หรือ functional style (Router Function) การใช้ ResponseEntity และ ServerResponse ให้ถูกต้องจะช่วยให้ API ของคุณมีความชัดเจน เข้าใจง่าย และสามารถทำงานร่วมกับ client ได้อย่างราบรื่น

แหล่งอ้างอิง


    Leave a Reply

    อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *