我是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);
}
即使在那之后,我也无法按预期获得错误代码和错误消息。
答案 0 :(得分:1)
根据您的控制器,它用来引发“ BusinessException”异常。但是您尚未实现在Controller Advisor中捕获该异常的方法“ GlobalExceptionHandler”。测试成功后,请在您的控制器顾问中包括以下方法。
@ExceptionHandler(BusinessException.class)
public ResponseEntity<String> handleBusinessException(BusinessException businessException ) {
return new ResponseEntity<>("Your specific error", HttpStatus.NOT_FOUND);
}
答案 1 :(得分:0)
您遇到的异常处理代码丢失,请参考https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.html和https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html
答案 2 :(得分:0)
如果两个输入都是无效的错误消息,则应该创建组合消息,而不是引发业务异常,然后您可以返回responseEntity作为快速解决方案:
返回新的ResponseEntity <>(“无效输入”,HttpStatus.NOT_FOUND);
答案 3 :(得分:0)
要通过@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");