![](/img/trans.png)
[英]Customizing HTTP response message during an error spring boot rest api
[英]Not able to return error code with message from rest API in Spring boot
我是Spring Boot的新手。 我已經在Spring Boot中實現了以下rest api:
@GetMapping(value = "/output")
public ResponseEntity<?> getListOfPOWithItem(@QueryParam("input1") String input1,
@QueryParam("input2") String input2)
throws BusinessException {
if (input1 == null) {
throw new BusinessException("Query param input1 is null or invalid");
}
if (input2 == null) {
throw new BusinessException("Query param input2 is null or invalid");
}
List<Output> outputList =
myService.getDetails(input1, input2);
if (outputList != null) {
return new ResponseEntity<List<Ouput>>(outputList, HttpStatus.OK);
}
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
Myservice中的getDetails()定義如下:
public List<Output> getDetails(String input1, String input2)
throws BusinessException {
String path = new StringBuilder().append(getBaseUrl()).append("/input1/")
.append(input1).append("/input2/").append(input2).toString();
try {
ResponseEntity<List<Output>> responseEntityList = restTemplate.exchange(path,
HttpMethod.GET, null, new ParameterizedTypeReference<List<Output>>() {});
List<Output> outputList = responseEntity.getBody();
if (responseEntityList.isEmpty()) {
throw new EntityNotFoundException("Input not found",
ExternalServicesErrorCode.NO_DATA_FOUND);
}
return outputList;
} catch (HttpStatusCodeException e) {
int statusCode = e.getStatusCode().value();
if (statusCode == Status.NOT_FOUND.getStatusCode()) {
throw new EntityNotFoundException("Data not found",
ExternalServicesErrorCode.NO_DATA_FOUND);
} else {
throw new BusinessException("Error in getting data", ExternalServicesErrorCode.SERVICE_ERROR);
}
}
}
問題是:調用此API進行無效輸入時,我得到500,而不是404和錯誤消息“找不到數據”。 誰能建議我在上面的代碼中進行哪些更改?
編輯:按照建議,我添加了以下課程:
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<ExceptionResponse>
handleAllExceptions(Exception ex,
WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now().toEpochMilli(),
ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(EntityNotFoundException.class)
public final ResponseEntity<ExceptionResponse> handleEntityNotFoundException(
EntityNotFoundException ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now().toEpochMilli(),
ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(exceptionResponse, HttpStatus.NO_CONTENT);
}
即使在那之后,我也無法按預期獲得錯誤代碼和錯誤消息。
根據您的控制器,它用於引發“ BusinessException”異常。 但是您尚未實現在Controller Advisor中捕獲該異常的方法“ GlobalExceptionHandler”。 測試成功后,請在您的控制器顧問中包括以下方法。
@ExceptionHandler(BusinessException.class)
public ResponseEntity<String> handleBusinessException(BusinessException businessException ) {
return new ResponseEntity<>("Your specific error", HttpStatus.NOT_FOUND);
}
如果兩個輸入都是無效錯誤消息,則應該創建組合消息,而不是引發業務異常,然后可以返回responseEntity作為快速解決方案:
返回新的ResponseEntity <>(“ Invalid input”,HttpStatus.NOT_FOUND);
要通過@RestControllerAdvice處理此修復程序,您應該創建一個自定義異常,其中包含httpStatus代碼和您要返回的消息
public class CustomBusinessException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
private final String status;
private final String requestMessage;
private final String description;
public CustomBusinessException (Throwable ex,String status, String requestMessage, String description) {
super(ex);
this.status = status;
this.requestMessage = requestMessage;
this.description = description;
}
//create getter and setter
}
通過您的自定義異常處理程序(@RestCOntrollerAdvice)處理此異常,並准備要像這樣發送的自定義響應
@ExceptionHandler({ CustomBusinessException .class })
public ResponseEntity<CustomBusinessResponse> handleAll(CustomBusinessException customBusinessException , WebRequest request) {
logger.error("Exception occured in NRACustomExceptionHandler :"+ExceptionUtils.getStackTrace(nraGatewayException));
CustomBusinessResponse response = new CustomBusinessResponse();
response.setMessage(customBusinessException.getRequestMessage());
response.setDescription(customBusinessException.getDescription());
return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.valueOf(Integer.parseInt(customBusinessException.getStatus())));
}
創建一個自定義響應類
public class NRAExceptionResponse {
private String message;
private String description;
//create getter and setter
}
拋出具有這樣發送狀態的自定義異常
throw new NRAGatewayException(e, "404","Invalid Input", "Invalid input 1 and input 2");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.