如果未提供請求正文 json,則如何處理 Spring Boot 中 pojo 或 bean 型別的 ResponseEntity 的自定義例外。
我正在嘗試通過將請求正文提供為 JSON 來從外部 API 獲取回應為 JSON。我可以這樣做。但是,如果未提供請求正文 JSON,那么我需要將回應作為 JSON 提供,例如 { msg : "Request Body is needed"}
@PostMapping(value="/postdata",produces = MediaType.APPLICATION_JSON_VALUE)
private ResponseEntity<DataResponse> postData(@RequestBody DataRequest json) throws JsonProcessingException {
String uri = "http://...."; //External API
ResponseEntity<String> response = null;
DataResponse data = null;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ObjectMapper obj = new ObjectMapper();
HttpEntity<String> entity = new HttpEntity<String>(obj.writeValueAsString(json),headers);
response = restTemplate.postForEntity(uri, entity, String.class);
String result = response.getBody().toString();
JSONObject jobj = new JSONObject(result);
System.out.println("jobj ===" jobj.getJSONObject("data").toString());
String data = jobj.getJSONObject("data").toString();
data = obj.readValue(jobj.toString(), DataResponse.class);
return ResponseEntity.status(HttpStatus.OK).body(segment);
}
// ...
if( user == null ) {
throw new userdefinedException("RequestBody is Required");
}
我試過像上面那樣使用,但在控制臺中沒有回應為空
如何處理這些型別的例外。
提前致謝
uj5u.com熱心網友回復:
在Controller中,API方法添加了這個條件
// for null check of object
if( user == null ) {
throw new UserNotFoundException("RequestBody is Missing");
}
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public class UserNotFoundException extends RuntimeException{
private static final long serialVersionUID = 1L;
public UserNotFoundException(String message) {
super(message);
}
}
@ControllerAdvice
@RestController
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleRequestBodyNotFound(UserNotFoundException ex, WebRequest request) {
ErrorMessage exceptionResponse = new ErrorMessage(new Date(), ex.getMessage(),request.getDescription(false));
//exceptionResponse.setTimestamp(LocalDateTime.now());
return new ResponseEntity<Object>(exceptionResponse,new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY.value());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345453.html
