【发布时间】:2020-07-21 05:36:57
【问题描述】:
下面的 Spring REST 代码返回给定ticketId 的列表。
可以在这段代码中抛出NullPointerException 吗?
NullPointerException 明确被TicketController 捕获:
catch (NullPointerException nullPointerException) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, nullPointerException.getMessage(), nullPointerException);
}
在检查票证 id 是否为 null 时的想法可能是:
if (ticketId == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ticket id cannot be null");
}
期望NullPointerException 会被抛出,但ResponseStatusException 会被抛出?
如果变量ticketId 是一个路径参数,它永远不能为空,因为在没有ticketId 的情况下点击基本网址/ 我收到:
There was an unexpected error (type=Method Not Allowed, status=405).
全部来源:
@RestController
public class TicketController {
private final TicketServiceImpl ticketServiceImpl;
public TicketController(TicketServiceImpl ticketServiceImpl) {
this.ticketServiceImpl = ticketServiceImpl;
}
@GetMapping(path = "/{ticketId}")
public ResponseEntity<List<TicketResponse>> getTicketsById(
@PathVariable("ticketId") final Long ticketId) {
try {
final List<TicketResponse> ticketsById = ticketServiceImpl.getAll(ticketId);
return new ResponseEntity<>(ticketsById, HttpStatus.OK);
}
catch (NullPointerException nullPointerException) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, nullPointerException.getMessage(), nullPointerException);
}
catch (TicketNotFoundException ticketNotFoundException) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Ticket id not found",
ticketNotFoundException);
}
}
}
@Service
public class TicketServiceImpl implements TicketService {
private final TicketRepository ticketRepository;
public TicketServiceImpl(TicketRepository ticketRepository) {
this.ticketRepository = ticketRepository;
}
@Override
public List<TicketResponse> getAll(Long ticketId) {
final List<TicketResponse> ticketResponselist = ticketRepository.findData(ticketId);
if (ticketId == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ticket id cannot be null");
}
else if (ticketResponselist.size() == 0) {
throw new TicketNotFoundException("ticket not found");
}
else {
return ticketResponselist;
}
}
}
@Repository
public interface TicketRepository {
public List<TicketResponse> findData(Long ticketId);
}
【问题讨论】:
-
虽然抛出异常需要时间,但这通常不是性能问题。将异常放在 catch 子句中并没有那么慢。所以问题变成了:1.你为什么关心和2.你是怎么测试的?您确定没有框架/情况可以抛出
NullPointerException吗?如果可以,那么生成更高级别/已检查的异常肯定是有意义的。
标签: java spring spring-boot rest model-view-controller