Return 404 for missing user or post

This commit is contained in:
Tim
2025-07-14 18:34:28 +08:00
parent d3870e9efc
commit 68410c7fd1

View File

@@ -1,5 +1,6 @@
package com.openisle.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -16,6 +17,15 @@ public class GlobalExceptionHandler {
.body(Map.of("error", ex.getMessage(), "field", ex.getField()));
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<?> handleIllegalArgumentException(IllegalArgumentException ex) {
String msg = ex.getMessage();
if (msg != null && (msg.contains("User not found") || msg.contains("Post not found"))) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", msg));
}
return ResponseEntity.badRequest().body(Map.of("error", msg));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(Exception ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));