Вы можете написать метод, как я назову его обработчик ответа в любом классе, а затем установить свой ответ в нем, как вам нравится.Пожалуйста, смотрите код ниже:
public class ResponseHandler {
public static ResponseEntity<Object> generateResponse(HttpStatus status, boolean error,String message, Object responseObj) {
Map<String, Object> map = new HashMap<String, Object>();
try {
map.put("timestamp", new Date());
map.put("status", status.value());
map.put("isSuccess", error);
map.put("message", message);
map.put("data", responseObj);
return new ResponseEntity<Object>(map,status);
} catch (Exception e) {
map.clear();
map.put("timestamp", new Date());
map.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
map.put("isSuccess",false);
map.put("message", e.getMessage());
map.put("data", null);
return new ResponseEntity<Object>(map,status);
}
}
}
Пример использования:
@RestController
public class UtilityController {
private static Logger LOGGER = LoggerFactory.getLogger(UtilityController.class);
@RequestMapping("/test")
ResponseEntity<Object> getAllCountry() {
LOGGER.info("Country list fetched");
return ResponseHandler.generateResponse(HttpStatus.OK, false, "Success", null);
}
}
Если у вас есть какие-либо другие вопросы, пожалуйста, дайте мне знать.