【发布时间】:2018-12-15 10:29:12
【问题描述】:
下面是我在 Spring boot 中的 ExceptionHandler 类
@RestControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({InvalidRequestException.class, PropertyReferenceException.class})
public final ResponseEntity<ExceptionDetails> handleInvalidRequestException(InvalidRequestException ex, WebRequest request) {
ExceptionDetails details = new ExceptionDetails(ex.getMessage(),request.getDescription(false), new Date());
return new ResponseEntity<ExceptionDetails>(details, HttpStatus.BAD_REQUEST);
}
}
下面是我的服务类中的代码。
@Override
public Page<Segment> listSegment(int pageNum, int size, String sortBy, String direction, String app) {
log.info("Starting to query the segment list");
Pageable pageable = createPageRequest(size, pageNum, sortBy, direction);
Pageable pageable = new PageRequest(page, size, dir, sortBy);
Page<Segment> resultPage = segmentRepository.findByApp(app,pageable);
if(pageNum > resultPage.getTotalPages() || resultPage.getContent().isEmpty()) {
log.info("No segment present");
throw new ResourceNotFoundException("No Segment Present");
}
log.info("Total segment successfully fetched is: "+resultPage.getContent().size());
if(resultPage.hasNext())
return new Page<>(resultPage.getContent(), true);
else
return new Page<>(resultPage.getContent());
}
在sortBy 中,如果我传递了一个无效的列名,那么这会抛出PropertyReferenceException,它不会像上面提供的代码那样被我的ExceptionHandler 捕获,我不知道为什么。
但是,如果我在我的服务层中使用 try-catch 块捕获此异常并抛出我的自定义 InvalidRequestException,那么它会被异常处理程序捕获。
请有人告诉我原因以及如何在我的 ExceptionHandler 中捕获 PropertyReferenceException
【问题讨论】:
-
发布代码格式正确,而不是引用文本,并发布异常的准确和完整的堆栈跟踪。
-
嗨@JBNizet,我已经更新了
-
您能发布自定义异常的代码吗?
标签: java spring spring-boot spring-restcontroller spring-rest