如何使用 ResponseEntity 来 return 来自 REST 调用的简单错误消息?
How do I use ResponseEntity to return simple error message from my REST call?
我有一个用 Java 和 Spring MVC 编写的网络应用程序。
有一个 REST Web 服务,当它工作时,我以 JSON 格式返回 Employee
。
但是如果出现错误,我会返回一个很大的 JSON 字符串,其中包含 HTML 错误页面,但不包含我的 sErrorMsg 字符串(错误示例 JSON 包含在下面)。
问题:如何让错误响应成为一个简单的 JSON 字符串,其中包含我的错误消息?
@RequestMapping(value = "/json/employee/{employeeId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Employee> getEmployee(@PathVariable("employeeId") int employeeId) throws Exception {
Employee employee = null;
String sErrorMsg = "";
try {
employee = employeeService.getEmployee(employeeId);
} catch (Exception x) {
sErrorMsg = "Error getting employee; "+x.getMessage();
// UPDATE:
// throw x; <<-- errant line here was causing the problem
//
}
ResponseEntity responseEntity = null;
if (ret != null) {
ResponseEntity responseEntity = ResponseEntity.ok(employee);
} else {
responseEntity = ResponseEntity.badRequest().body(sErrorMsg);
}
return responseEntity;
}
错误JSON ...
{"readyState":4,"responseText":"<!doctype html><html lang=\"en\"><head><title>HTTP Status 500 – Internal Server Error</title><style type=\"text/css\">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line /* the rest of the HTML which contains a length Java stack trace ... */ }
问题是我自己造成的 throw x
在这里...
} catch (Exception x) {
sErrorMsg = "Error getting employee; "+x.getMessage();
throw x; // <<-- errant line here was causing the problem
}
我删除了 throw x;
,一切正常。
我做了这样的事情:
@GetMapping("/get/findByTsId")
public ResponseEntity<JsonPayLoad> findByTsId(String id) throws JsonProcessingException{
try{
JsonPayLoad payload = this.splunkService.findByTsId(id);
log.info("search request for TsId \t {} received at ->>> {}",id, LocalDateTime.now());
log.info("match found \n {}", payload.toString());
return ResponseEntity.ok(payload);
} catch(NullPointerException nullPointerException){
ObjectMapper mapper = new ObjectMapper();
String message = "{\"result\": \"no match found for id: " + id+ "\"}";
JsonPayLoad jsonPayLoad = new JsonPayLoad() ;
JsonNode messageValue = mapper.readTree(message);
jsonPayLoad.setPayload(messageValue);
jsonPayLoad.setTimeStamp((LocalDateTime.now()).toString());
log.info("search request for TsId \t {} received at ->>> {}",id, LocalDateTime.now());
log.info("no match found \n {}", jsonPayLoad);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(jsonPayLoad);
}
}
我有一个用 Java 和 Spring MVC 编写的网络应用程序。
有一个 REST Web 服务,当它工作时,我以 JSON 格式返回 Employee
。
但是如果出现错误,我会返回一个很大的 JSON 字符串,其中包含 HTML 错误页面,但不包含我的 sErrorMsg 字符串(错误示例 JSON 包含在下面)。
问题:如何让错误响应成为一个简单的 JSON 字符串,其中包含我的错误消息?
@RequestMapping(value = "/json/employee/{employeeId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Employee> getEmployee(@PathVariable("employeeId") int employeeId) throws Exception {
Employee employee = null;
String sErrorMsg = "";
try {
employee = employeeService.getEmployee(employeeId);
} catch (Exception x) {
sErrorMsg = "Error getting employee; "+x.getMessage();
// UPDATE:
// throw x; <<-- errant line here was causing the problem
//
}
ResponseEntity responseEntity = null;
if (ret != null) {
ResponseEntity responseEntity = ResponseEntity.ok(employee);
} else {
responseEntity = ResponseEntity.badRequest().body(sErrorMsg);
}
return responseEntity;
}
错误JSON ...
{"readyState":4,"responseText":"<!doctype html><html lang=\"en\"><head><title>HTTP Status 500 – Internal Server Error</title><style type=\"text/css\">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line /* the rest of the HTML which contains a length Java stack trace ... */ }
问题是我自己造成的 throw x
在这里...
} catch (Exception x) {
sErrorMsg = "Error getting employee; "+x.getMessage();
throw x; // <<-- errant line here was causing the problem
}
我删除了 throw x;
,一切正常。
我做了这样的事情:
@GetMapping("/get/findByTsId")
public ResponseEntity<JsonPayLoad> findByTsId(String id) throws JsonProcessingException{
try{
JsonPayLoad payload = this.splunkService.findByTsId(id);
log.info("search request for TsId \t {} received at ->>> {}",id, LocalDateTime.now());
log.info("match found \n {}", payload.toString());
return ResponseEntity.ok(payload);
} catch(NullPointerException nullPointerException){
ObjectMapper mapper = new ObjectMapper();
String message = "{\"result\": \"no match found for id: " + id+ "\"}";
JsonPayLoad jsonPayLoad = new JsonPayLoad() ;
JsonNode messageValue = mapper.readTree(message);
jsonPayLoad.setPayload(messageValue);
jsonPayLoad.setTimeStamp((LocalDateTime.now()).toString());
log.info("search request for TsId \t {} received at ->>> {}",id, LocalDateTime.now());
log.info("no match found \n {}", jsonPayLoad);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(jsonPayLoad);
}
}